Is the following guaranteed to work or implementation defined?
unsigned int a = 4294967294;
signed int b = a;
The value of b
is -2
on gcc.
From C99 (§6.3.1.3/3) Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
The conversion of a
value to signed int
is implementation-defined (as you correctly mentioned because of 6.3.1.3p3) . On some systems for example it can be INT_MAX
(saturating conversion).
For gcc
the implementation behavior is defined here:
The result of, or the signal raised by, converting an integer to a signed integer type when the value cannot be represented in an object of that type (C90 6.2.1.2, C99 6.3.1.3).
For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.
http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html
来源:https://stackoverflow.com/questions/13636397/unsigned-to-signed-conversion-in-c