In addition to forcing inlining, macros can also be detrimental to speed if they are not carefully written so as not to evaluate their arguments twice. Take, for example, this low-functional macro and its built-in function:
#define square(x) ((x)*(x)) inline long square(long x) { return x*x; }
Now when you call them with the square(foo) variable, they are equivalent. The vesion macro expands to ((foo)*(foo)) , which is one multiplication, just like a function if it is built-in.
However, if you call them using square(expensiveComputation(foo)) , the result of the macro is that expensiveComputation() is called twice. In contrast, an inline function behaves like any function: its argument is evaluated once before the function body is executed.
Of course, you can write a macro using the gnu extension of compound statements (see http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html for documentation on this) to avoid double-valuation:
#define square(x) ({ \ long square_temp_variable = (x); \ square_temp_variable*square_temp_variable; \ })
But this is a lot of trouble, and it makes the code unsportsmanlike. So, it is better to stick with the built-in functions.
source share