One More Reason to Avoid Macros

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.

See also  Innovation in Crypto Trading Bots

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist