| |||||
Technical Support Support Resources
Product Information | GENERAL: #DEFINE GENERATES WRONG RESULTSInformation in this article applies to:
QUESTIONI 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 ANSWERThe #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: Tuesday, December 18, 2007 | ||||
| |||||