ARM Technical Support Knowledge Articles

#DEFINE GENERATES WRONG RESULTS

Applies to: General Topics

Answer


Information in this article applies to:


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

Article last edited on: 2007-12-18 00:42:21

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential