By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,464 Members | 1,074 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,464 IT Pros & Developers. It's quick & easy.

unexpected output

P: 3
Below code outputs garbage value. any idea why so?
Expand|Select|Wrap|Line Numbers
  1. unsigned variable1=1;
  2. int variable2=-4;
  3. printf("%u",variable1+variable2);
  4.  
3 Weeks Ago #1
Share this Question
Share on Google+
5 Replies


Expert 100+
P: 202
Below code outputs garbage value. any idea why so?
What garbage value? Negative numbers are represented in 2's complement form.
3 Weeks Ago #2

P: 3
Thanks for replying. the outputs says 4294967293 which is nowhere near what i interpret.
3 Weeks Ago #3

Expert 100+
P: 202
You gotta think the way the machine is processing stuff.

Binary of 4 = 100 , 1's complement representation: 011, 2's complement representation: 100

But, sizeof(int) = 4 bytes = 32 bits which means the machine is processing numbers with respect to 32 bits.

Therefore, -4 is represented as 11111111 11111111 11111111 11111100

which is equivalent to (2^32-1)-3

Hence, variable1+variable2 means ((2^32-1)-3)+1 which results in 4294967293 and is not a garbage value.
3 Weeks Ago #4

Expert 100+
P: 2,404
One of the arguments to printf() is an expression that adds an unsigned int variable to an int variable. The compiler uses the usual arithmetic conversions to resolve this type discrepancy before evaluating the expression: the int variable is implicitly cast to unsigned int.

dev7060's post explains the rest.
2 Weeks Ago #5

P: 3
Hi thanks to both. i understand it now :)
1 Week Ago #6

Post your reply

Sign in to post your reply or Sign up for a free account.