Why does this code show the negative value? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does this code show the negative value?

I suspect it has something to do with signed and unsigned, but, why does it show -23 instead of 23? https://code.sololearn.com/czOx12ksBB5l/?ref=app

17th Dec 2019, 7:11 AM
Fernando Pozzetti
Fernando Pozzetti - avatar
4 Answers
+ 2
<i> is an unsigned int, and <c> is a signed int. When you compare two integral values with different sign, the RHS operand will silently be converted to the same type of LHS. In your case, your condition `if(i > c)` evaluates to false, because during the comparison, <c> is converted from signed int to unsigned int. To understand what I mean try `printf("%u", c);` this will show you why a 23 (as unsigned int) is considered less than -23 (as unsigned int). Hth, cmiiw
17th Dec 2019, 8:27 AM
Ipang
+ 3
-23 as unsigned int = 4294967273 Binary or not, 23 is less than that big value : )
17th Dec 2019, 8:36 AM
Ipang
+ 2
Thank you so much! I got it from the C challenges in SL. It was a very tricky question for me. I guess we can learn something everyday!
17th Dec 2019, 8:42 AM
Fernando Pozzetti
Fernando Pozzetti - avatar
+ 2
Thank you also, yes there's always a new thing to learn everyday : )
17th Dec 2019, 8:44 AM
Ipang