Home > Blogs > 30 C++ Tips in 30 Days: Tip # 15 another reason to avoid macros

30 C++ Tips in 30 Days: Tip # 15 another reason to avoid macros

By  Dec 6, 2007

Topics: Programming, C/C++

Macros should be avoided for many good reasons. One particularly good reason is the erratic behavior of macros with side effects.

Consider the following macro which looks rather harmless:

#define twice(x) ((x)+(x))

It's well parenthesized and performs a simple addition operation. What can go wrong with it? A lot. When twice() takes an argument with side-effects, the results can be unpredictable:

int n = 1;
int sum= twice(++n);  //guess what?

Since ++n equals 2, one might expect (rather naively) that sum would be 4. However, that's not the result you'll get. The expression twice(++n) is expanded as ((++n)+(++n)). To conclude, avoid function-like macros.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed