Question

A program that I'm trying to decode includes the following line:

#define nn(sp)   ((sp)->nn)

From the context (not shown), I'm pretty sure that 'sp' is a pointer to a struct which contains 'nn' as one of its variables.

In the expression "((sp)->nn)", does the inner set of parentheses serve any conceivable purpose? If not, might the outer set of parentheses also serve no purpose?

Was it helpful?

Solution

#define nn(sp)   ((sp)->nn)

The inner parentheses are required. If you pass a pointer like p + 10 or *p to nn macro, you would get some troubles without the inner parentheses as -> has higher precedence than + and unary *.

The outer parentheses are not required here as the expression involves a postfix operation and no operator has greater precedence than postfix operators.

OTHER TIPS

It's a general defensive strategy to wrap macro arguments and the entire substituted text in parens. This protects the macro from unintended precendence changes.

Consider if the sp argument is a dereferenced pointer.

nn(*x)  //--> ((*x)->nn)

But without the inner parens:

nn(*x)  //--> (*x->nn)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top