Search code examples
ccharsigned

Why does the following programme gives output as "-128" despite its value assigned as "128"?


#include <stdio.h>
#include <stdlib.h>

int main()
{
    signed char chr=128;

    printf("%d\n",chr);
    
    return 0;
}

Solution

  • Do you know about integer limits? A char value takes up 1 byte. A byte is usually 8 bits. To calculate the limit through the number of bits, the calculation is 2^n-1 meaning an integer with 8 bits has a range from 0 to 255 when unsigned. Since your variable is signed, it allocates a bit to the sign, meaning it has a range from -128 to 127. Since you assigned it as 128, it overflowed, rolling back over to -128. If your program doesn't use negative numbers, you should use signed char, otherwise you might want to use a short which is 2 bytes.