[prog] C code

Katie Bechtold katie at katie-and-rob.org
Mon May 2 15:28:10 EST 2005


On Mon, May 02, 2005 at 06:11:59AM +0100, Noir wrote:
> #define SIX    1 + 1
> #define NINE   2 + 1 
> ...
> SIX * NINE

The issue here is order of operations.    "SIX * NINE" is replaced
with "1 + 1 * 2 + 1".  Since the multiplication operator binds more
"strongly" to operands than does the addition operator, it evalutes
this expression as though it read "1 + (1 * 2) + 1", which evalutes
to "1 + 2 + 1", hence the result 4.

You can be more explicit about the order of operations you want by
using parentheses in the #define statement like so:

#define SIX    (1 + 1)
#define NINE   (2 + 1)

The use of parentheses in #define statements is considered good
programming practice, as it prevents problems like the one you
experienced.

-- 
Katie Bechtold         http://katie-and-rob.org/




More information about the Programming mailing list