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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.