volatile unsigned char a; a = 3; printf("%u\n", a * 100);
The output is 11264. Why?
Any reply would be greatly appreciated.
A footnote: 3*100 = 300 decimal or 0x12c.
11264 decimal is 0x2c00.
So if 3*100 is computed as an 8-bit expression, then the argument to printf() is 0x2c while printf() expects to pick up two bytes and manages to find 0x2c and 0x00.
With integer promotion enabled, then 3*100 will always be computed with at least 16-bit precision and a 16-bit value will be send to printf() - so the correct answer will be printed.
Hi Per Westermark,
Thanks for you quick reply.
I check the option Enable ANSI integer promotion rules and it is enabled. If I disable it, the output is the same. It seems that Keil complier does not promote varible a or constant 3 to an integer.
If I change code to this:
printf("%u\n", (unsigned int)a * 100);
or
printf("%u\n", a * (unsigned int)100);
The result is correct.
If C51 doesn't do integer promotion and sends int-size values to printf() even with integer promotion on, then I would recommend you to send a message to Keil support.