Motivated from a code snippet on this blog under "What happens when I mix signed and unsigned integers?" I decided to run it with few different values of signed and unsigned integers and observe the behaviour.
Here is the original snippet (slightly modified, however intent is still same)
#include <stdio.h>
int main(void)
{
unsigned int a = 6;
int b = -20;
int c = (a+b > 6);
unsigned int d = a+b;
printf("<%d,%u>", c, d);
}
OUTPUT: <1,4294967282>
Now when I run the same program for a = 6
and b = -1
OUTPUT: <0,5>
If I understand Integral Promotion rule of C language correctly, b=-1
should have been promoted to an unsigned integer, that would have made it 4294967295
. And just like in case of original example we should get <1,4294967301>
. But that is not what we got.
The only reason for this behaviour I could think of was that these implicit type conversions happen after the arithmetic operation. However, the same blog post also says that signed integers are first promoted and then evaluation takes place, which invalidates my reasoning.
What is the real reason for this behaviour? And how the two examples different from each other.
P.S I understand that there are many questions on SO which are similar/related to this problem. But I have not come across any question that addresses this problem particularly or helps in understanding such code snippet. If found to be a duplicate, I would gladly accept this question be closed.