"Sputnik" help |

Sputnik
Help

Operator Precedence Problems

You may have noticed that in most of the macro definition examples shown above,
each occurrence of a macro argument name had parentheses around it. In addition,
another pair of parentheses usually surround the entire macro definition. Here
is why it is best to write

macros that way.

Suppose you define a macro as follows,

#defineCEIL_DIV(x,y)(x+y-1)/y

whose purpose is to divide, rounding up. (One use for this operation is to compute how many int objects are needed to hold a certain number of char objects.) Then suppose it is used as follows:

$a=CEIL_DIV($b&$c,@Int32Size);

Should be this right? Nope.

$a=($b&$c+@Int32Size-1)/@Int32Size;

This does not do what is intended. The operator-precedence rules of **Sputnik**
make it equivalent to this:

$a=($b&($c+@Int32Size-1))/@Int32Size;

What we want is this:

$a=((b&c)+@Int32Size-1))/@Int32Size;

Defining the macro as

#defineCEIL_DIV(x,y)((x)+(y)-1)/(y)

provides the desired result.

Unintended grouping can result in another way. Consider sizeof **CEIL_DIV**(1,
2). That has the appearance of a **Sputnik** expression that would
compute the size of the type of **CEIL_DIV**(1, 2), but in fact
it means something very different. Here is what it expands to:

Say((1)+(2)-1)/(2)

This would take the size of an integer and divide it by two. The precedence rules have put the division outside the Say when it was intended to be inside.

Parentheses around the entire macro definition prevent such problems. Here,
then, is the recommended way to define **CEIL_DIV**:

#defineCEIL_DIV(x,y)(((x)+(y)-1)/(y))

Contact

Cheryl (uberfox@hotmail.com)

Homepage

http://ubersoft.org