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
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.