Preprocessor Confusion?

Why does Keil's C51 preprocessor work fine with:

#define MULTPLR (unsigned char)((float)9.114584e-5 * (float)18432000 / (float)12)

...but consistently give the wrong result with:

#define MULTPLR (unsigned char)((float)9.114584e-5 * (float)18432000 / (float)6)

???

Parents
  • The preprocessor doesn't compute the numbers - it just performs any copy/paste replacements and leaves it to the compiler.

    But maybe you should tell us what happens, and what you did expect to happen?

    Anyway - the first expression gives the value 140,00001024 which should be truncated to 140. This fits into an 8-bit unsigned integer.

    The second expression gives the value 280,00002048 which is too large for your unsigned char. The allowed range is only 0 to 255. 280 decimal is 0x0118. If you only keep the least significant 8 bits, you get 0x18 or 24 in decimal.

    Always use pen and paper or pocket calculator or similar and test things logically step-by-step. There is normally always a logical explanation to things.

Reply
  • The preprocessor doesn't compute the numbers - it just performs any copy/paste replacements and leaves it to the compiler.

    But maybe you should tell us what happens, and what you did expect to happen?

    Anyway - the first expression gives the value 140,00001024 which should be truncated to 140. This fits into an 8-bit unsigned integer.

    The second expression gives the value 280,00002048 which is too large for your unsigned char. The allowed range is only 0 to 255. 280 decimal is 0x0118. If you only keep the least significant 8 bits, you get 0x18 or 24 in decimal.

    Always use pen and paper or pocket calculator or similar and test things logically step-by-step. There is normally always a logical explanation to things.

Children
More questions in this forum