In the following code:
#include "stdio.h"
signed char a= 0x80;
unsigned char b= 0x01;
void main (void)
{
if(b*a>1)
printf("promoted\n");
else if (b*a<1)
printf("why doesnt promotion work?");
while(1);
}
I expected “promoted’ to be printed. But it doesnt. Why?
If I can the datatypes to signed and unsigned int, and have a as a negative number, eg, 0x80000000 and b as a positive number, 0x01, “promoted” gets printed as expected.
PLZ HELP me understand what the problem is!
You’ve just been caught by the messy type-promotion rules of C.
In C, intermediates of integral type smaller than
intare automatically promoted toint.So you have:
0x80gets signed extended to typeint:So the result is
-128and thus is less than1.When you use type
intandunsigned int, both operands get promoted tounsigned int.0x80000000 * 0x01 = 0x80000000as an unsigned integer is bigger than1.So here’s the side-by-side comparison of the type promotion that’s taking place:
Here’s a reference to the type-promotion rules of C.