#include <stdio.h>
{
char num = 127;
num = num + 1;
printf("%d", num);
return 0;
}
Output is : -128 should I add output shot
#include <stdio.h>
{
char num = 127;
num = num + 1;
printf("%d", num);
return 0;
}
Output is : -128 should I add output shot
char
is a signed byte, that's why you are seeing that value.as others mentioned you should read Range of signed char
but to quickly see how it works you can take a look at this example,
char
is a that, on most systems, takes 1 byte (8 bits). Your implementation seems to havechar
represent a signed type, however on other implementations it could be unsigned. The maximum value for a signed type is 2^(n-1)-1, where n is the number of bits. So the maximum value of char is 2^(8-1)-1=2^7-1=128-1=127. The minimum value is actually -2^(n-1). This means the minimun value is -128. When you add something that goes over the maximum value, it overflows and loops back to the minimum value. Hence, 127+1=-128 if you are doingchar
arithmetic.You never use
char
for arithmetic. Usesigned char
orunsigned char
instead. If you replace yourchar
withunsigned char
the program would print 128 as expected. Just note that the overflow can still happen (unsigned types have a range from 0 to 2^n-1, sounsigned char
overflows if you add 1 to 255, giving you 0).