In the following program, the line 5 does give overflow warning as expected, but surprisingly the line 4 doesn\'t give any warning in GCC: http://www.ideone.com/U0
Well, line 5 is an obvious error that any compiler can see directly, and always an error. Line 4 would require at least some data flow analysis to discover the error. Perhaps this isn't done with the settings used at the site, or perhaps the compiler writers didn't consider this important enough to figure it out.
Post GCC 4.3, the semantics of -Wconversion
have been updated to detect implicit conversions that might change a value, but you have to enable -Wsign-conversion
as well, because otherwise you won't get a warning for code that might change the sign of a number due to coercion between signed and unsigned types.
Contrary to what Crazy Eddie is saying, prior to GCC 4.3 (which hadn't been released yet at the time) -Wconversion
didn't generically check for problems introduced by implicit type conversion and the like. Rather, it checked whether your program would behave differently than it would have behaved if it had used old-style K&R function prototypes.
This not only meant that it didn't give a warning on all implicit type conversion / coercion problems, but it also meant that some good code gave an unnecessary warning. And of course, you'd get no error with g++
because such prototypes aren't valid C++ anyway.
In the general case of assigning an int
value to a char
object, the compiler doesn't know whether the int
is out of range of the char
.
Look at the actual warning more closely:
warning: overflow in implicit constant conversion
It is in this specific case, where a constant is being converted to char
that the compiler is able to warn you. Likewise, if you changed the declaration of i
to be const
:
const int i = 256;
you will also get the warning, because the value being assigned to c2
is a constant expression.
Note also that the warning is somewhat misleading as the conversion does not technically "overflow." Arithmetic overflow yields undefined behavior in C++. A narrowing conversion (like int
to char
, if int
has a larger range than char
) yields some implementation-defined conversion.
-Wall
doesn't include many options. -Wconversion
is one of them and warns about the behavior you're interested in.
See http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html