
Patrick B. answered 10/05/19
Math and computer tutor/teacher
READABILITY
macros require lots of parenthesis to make sure this get expanded properly by the pre-processor,
which does simple TEXTUAL substitutions...
For example:
#define SQUARE_IT(x) = (x*x)
so the call to SQUARE_IT( 2+1)
expands to
(2+1*2+1) = 2+2+1 = 5
when you meant to get 3*3=9
The proper implementation is:
#define SQUARE_IT(x) = ((x) * (x))
which then expands to
(2+1)*(2+1) = 9
At the very least, you have to call the macro as:
SQUARE_IT((2+1))
But you know the rule... NEVER rely on the programmer to handle that...
always create ROBUST APIs...
However, using an inline function:
inline double SQUARE_IT(x) { return(x*x); }
the result of SQUARE_IT(3) is pass by value,
so you get the 9, no questions asked...
the disadvantage is that the inline keyword is only
a REQUEST to the compiler to expand the body of
the function inline, replacing function call with the
contents of the function in it's body and doing pass by value.
It is an amazing capability of the compiler to do that!!!
If the function body is too complicated, the compiler will raise
a warning saying the function cannot be compiled inline.
Ex. functions containing loops cannot be compiled inline.
I have compiled functions containing one IF statement inline..
typical examples are MIN, MAX functions, swap functions,
mathematical functions of x, for calculus or numerical
approximations, etc.
They must be SHORT, SIMPLE, and mundane.... typically doing one
operation and that's it. They are 1-2 lines of code...
anything more complicated than that, and the compiler will say NO