2012年3月19日星期一

inline and macro difference

First let's talk about the difference between macro and function

1. macro is done before compile, that's also why it is called pre-compile. So first of all, we use macro body to replace macro name. Then we do compile.

On the other hand, function is executed after compile. Actually, it is called in the process of execution. So we can see that macro take compile time and function take execution time.

2. Because we need to "call" function, we need to pay for some resource(cost). We need to keep the state, and then go into the called function, after "call" finish, we need to go back the function which call others. Then we need to recover state.

On the other hand, all these operation above will never happen in macro. What macro do is just string replacement(string! not other type). So the argument of macro will not occupy memory space. But function argument need memory space, since argument is variable info transfer. Argument is function's local variable. Also, we do not need to do computation for macro argument. Function is give the value of argument. Here, we use value which will lead to computation.

3. As we said above, macro is string replacement. But argument of function can be any type.
-----------------

What inline do is to "embed" its code to the function which call it. So we can save cost to call it.
We need be careful about inline function must be very simple. No loop, if else, etc.

PS: some compiler will handle simple function as inline automatically. Some complex function, even you declare it is inline, compile will not do so.
---------

NO grammar examination for MACRO! Inline will have grammar exam during compiling. That is the reason why most programmer choose inline but not macro.

没有评论: