Search code examples
c++charsigned

Getting Wrong Number Of Char Variable


in below code when i run it i get y=-124 and z=4294967172 can you explain me?? (tested that if x<128 there isnt any problem)

char x=132;
signed y=x;
unsigned z=x;
cout<<y<<endl;
cout<<z<<endl;

Solution

  • char is 8-bits, so when you write char x = 132, you actually do this:

    x = 1000 0100
    

    signed int and unsigned int both are 32-bits, and whenever you assign the value of a 'smaller' variable into a 'larger' one, the system uses sign extension, i.e. copies the sign bit to every bit to the left. So the value becomes:

    1111 1111 1111 1111 1111 1111 1000 0100
    

    If you interpret it as a signed value, it's -124, and as an unsigned value it's 4294967172.

    Moreover, if you define the char as unsigned in the first line, you would always get 132, as sign extension is not done for unsigned values.