0

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;
1
  • 2
    @iammilind: That is completely wrong. Even if there are unnamed padding bytes following x, they cannot in any way affect the semantics of the program. Commented Jan 8, 2012 at 9:59

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

wow thanks,very interesting thing i got here.also thanks to James McNellis to complete the answer and showed me the way to solve this
2

chars are only 8-bit, which means they can only hold 256 values including 0. You're using a signed char, which means half the values are reserved for negative numbers, making the maximum positive value 127.

2 Comments

thanks,but how about the value of z??its unsigned but it doesnt show 132
The value of z that you're getting looks to be the maximum value of an unsigned 32-bit integer, minus the value of x.
1

After first line x is 10000100 (132 is 10000100b) and it's the -124 value in machine (see here).
So after second line y is -124.
And after 3rd line z is 111...1110000100b. There are 1s on the higher bits because you're setting a negative number but when you print compiler prints it's binary value because z is unsigned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.