Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Jul 16, 1999

One More Reason to Avoid Macros

Even macros that look harmless can have detrimental effects. For example:

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

The macro, twice, is well parenthesized and performs a simple addition operation. Despite its simplicity, there can still be problems. When twice takes an expression with side effects as an argument, it yields unexpected results:

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

Since ++n equals 2, you might assume (rather naively) that sum would be 4, but it isn't. The expression twice(++n) is expanded as ((++n)+(++n)). However, if you had used an ordinary function instead of a macro, like this

 
inline int  twice(int x) { return x+x; }

The result will be 4, as expected.

Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date