The inline function, as an additional feature in C + +, is more reliable than the macro (#define) in traditional C (at least error-prone) when it is necessary to write functional code for a short, similar function.
#define SQUARE(X) X*X
The working mechanism of a macro is "character substitution."
a = SQUARE(5.0); // a = 5.0*5.0 b = SQUARE(4.57.5); // b = 4.5 + 7.5 * 4.5 + 7.5 c = SUQARE(d++); // c = d++ * d++;
In these three cases, only the a = SQUARE(5.0);
conventional design intent is met. Although you can avoid some problems by adding "()".
#define SQUARE(X) ((X) * (X))
There is still a problem. Because the macro's parameters are not "value passing". c = SQUARE(d++);
will still cause "d++" to execute two times, which may be different from conventional assumptions.
Therefore, if you need to write a macro similar to a function, consider using the C + + inline function instead.
inline and macro