What are the precautions that must be taken care to use macros in ‘C’? 5m Dec 2009

By | August 8, 2016

What are the precautions that must be taken care to use macros in ‘C’?

 

Caution in using macros

You should be very careful in using Macros. In particular the textual substitution means that arithmetic expressions are liable to be corrupted by the order of evaluation rules (precedence rules). Here is an example of a macro, which won’t work.

#define DOUBLE(n) n + n

Now if we have a statement,

z = DOUBLE(p) * q;

This will be expanded to

z = p + p * q;

And since * has a higher priority than +, the compiler will treat it as.

z = p + (p * q);

The problem can be solved using a more robust definition of DOUBLE

#define DOUBLE(n) (n + n)

Here, the braces around the definition force the expression to be evaluated before any surrounding operators are applied. This should make the macro more reliable.