#include <stdio.h>
int main()
{
signed char x = 0;
for (; x >= 0; x++);
printf("%d\n", x);
return 0;
}
The output of this code is -128. Can anyone explain why?
#include <stdio.h>
int main()
{
signed char x = 0;
for (; x >= 0; x++);
printf("%d\n", x);
return 0;
}
The output of this code is -128. Can anyone explain why?
Implementation-defined behavior
signed char x = 0; for (; x >= 0; x++);
iterates x
from 0 up to 127 (SCHAR_MAX
), all OK so far.
On the next iteration, x++
acting like x = x + 1;
, attempts to assign 128 to the signed char x
. As that is out of signed char
range:
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.
(C spec relating to conversions to a signed type)
A common implementation-defined result is to wrap around to -128 or SCHAR_MIN
. Other results could have happened, like assigning a max value of 127 resulting in an infinitive loop.
There is no signed integer overflow, just an out of range assignment.
Code is not highly portable and should be avoided.
It is implementation-defined behaviour.
on x86 platform all known to me compilers, when x
is 127 and you add 1
it performs unsigned addition and the result is 0b10000000 which in two's complement signed integer format is -128
As x
is -128
the loop terminates and -128
is printed out