Keil Logo

GENERAL: #DEFINE Generates Wrong Results


Information in this article applies to:

  • C51 All Versions
  • C166 All Versions
  • C251 All Versions

QUESTION

I have found a serious problem when I use simple constants in a #define statement. In the following code the constant is not divided:

if (value >= (MAX_MSG_LEN/4))

The value will not be (MAX_MSG_LEN/4) it is just MAX_MSG_LEN.

MAX_MSG_LEN is defined as follows:

#define MAX_LEN      16
#define MAX_MSG_LEN  MAX_LEN+3

ANSWER

The #define is a pure text replacement utility. So you have effectively written if (value >= (16+3/4)). The ANSI C compiler calculations plain numbers with the arithmetic rules for int variables. Therefore, 3/4 is calculated first which results in 0 and the result of the complete calculation is just 16. This lets you believe that the compiler does not divide.

As a general rule, it is recommended that you use parenthesis in #define statements. For example:

#define MAX_MSG_LEN (MAX_LEN+3)

This avoids simple programming mistakes as you had above.

MORE INFORMATION

SEE ALSO


Last Reviewed: Thursday, February 25, 2021


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.