Is this undefined behavior?
It prints -128
as the result:
#include<stdio.h>
int main()
{
char i=-128;
i=-i;
printf("%d",i);
}
Please explain.
chars in 'C' are used to represent characters. Numbers representing characters in all code pages are always positive.
unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.
The two's complement of -128 in an 8-bit signed value is -128.
Look at the binary values:
Original value: 10000000
Complement: 01111111
Increment: 10000000
This is not undefined behavior. Assuming type char
is signed in your platform, it is implementation defined behavior. (C99, 6.3.1.3p3)
i = -i
;
the i
in -i
is first promoted to int
, so -i
is 128
and then 128
is converted to char
by the integer conversions.
Here is the paragraph of the Standard that says the conversion of 128
to char
is implementation defined:
(C99, 6.3.1.3p3) 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.
EDIT: while it is implementation defined, there is a common implementation behavior between most implementations. Here is what gcc
(and most other compilers do) documents to do:
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
Note that not all compilers behave this way. Some (DSP) compilers just saturate. In this case (and still assuming a signed char
), after i = -i;
the value of i
would be 127
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With