10

Possible Duplicate:
g++ -Wall not warning about double-> int cast

Per the question here, direct conversion from double/float to unsigned integer is not portable. I found I had a few cases in my code where this happens and I would like to tell g++ to warn me if this occurs, but I can't find such an option. Does anyone know if there is an option to do this?

Note: I do see -Wconversion, but that also warns about all kinds of other conversions that I don't care about (like converting int to unsigned int, which is portable per the standard).

Edit: Here's a code example for which I would like to see a warning:

double dblNumber = -234;
unsigned long uintNumber = dblNumber;

On one version of g++, this gives me an integer value of 0xFFFFFF16 (which is -234 in 2's complement) . On another it gives me 0. Clearly the code is ambiguous, which is why it is understandably not considered portable.

4

2 回答 2

4

我知道您说您不想使用-Wconversion,但它会警告您关心的问题,并且至少在 g++ 4.5 中转换longunsigned long(例如)时不会发出警告。对于它警告您正在执行合法所需转换的任何其他情况,只需将其转换为。您未来的维护者将非常感谢您明确表示正在进行已知的转换,而不是从代码上下文中猜测它是否是有意的。

于 2012-12-06T21:28:20.367 回答
1

When a float to int implicit conversion is done, and the truncated value cannot fit the destination type, then the behaviour is undefined, as your example nicely illustrates it.

If the only tool provided by g++ is the -Wconversion, perhaps you should make your own tool to filter the warnings out to your convenience (I am thinking the usual sed, awk, perl or php, but it depends on the availability of these tools on your system, and maybe you can do something similar directly from your IDE if you use one).

You can also use specific pragma directives of gcc to restrict conversion checks to specific files, or even specific code parts.

Any other programatic method used to pinpoint in your code where problematic conversions happen could certainly be used to insert explicit casts, which is the goal your should be aiming for.

于 2012-12-06T21:47:02.607 回答