|ARM Technical Support Knowledge Articles|
Applies to: General Topics
Information in this article applies to:
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
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.
Article last edited on: 2007-12-18 00:42:21
Did you find this article helpful? Yes No
How can we improve this article?