This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

printf outputs wrong result when do multiplication

volatile unsigned char a;

a = 3;
printf("%u\n", a * 100);

The output is 11264. Why?

Any reply would be greatly appreciated.

Parents
  • 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.

Reply
  • 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.

Children