Use inline Instead of #define to Define Short Functions

The traditional C way to create the near-equivalent of an inline function is to use a #define macro definition:

#define Cube(X) X*X*X

This leads the preprocessor to do text substitution, with X being replaced by the corresponding argument to Cube():

y = Cube(x);      // replaced with y = x*x*x;y = Cube(x + z++);  // replaced with x + z++*x + z++*x + z++;

Because the preprocessor uses text substitution instead of true passing of arguments, using such macros can lead to unexpected and incorrect results. Such errors can be reduced by using lots of parentheses in the macro to ensure the correct order of operations:

#define Cube(X) ((X)*(X)*(X))

Even this, however, doesn’t deal with cases such ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.