What is the difference between a macro and an inline function in C
In Category C/C++
The fundamental difference between a macro and an inline function is that they are handled in different phases of binary creation. A macro is expanded during pre-processing stage by the “cpp” command. The “cpp” command is the C preprocessor. On the other hand, the inline functions are handled by the actual compiler “gcc“.
As the preprocessor is less intelligent, it does blind code replacements wherever it finds usage of a macro. A function described in a macro form doesn’t look nice in terms of code readability. Also arguments taken by a macro do not carry their type and often cause compilation errors that are not so obvious to fix.
Where as an inline function is more powerful than a macro and it is like any other function in the C source code with a keyword “inline” attached to it. Let us look at simple inline function given below.
inline int sum(int a, int b)
{
return (a+b);
}
All inline functions behave like functions when no optimization flag is set during compilation. That means you will find a symbol with the names of all inline functions in the target binary (ELF) file.
But when optimization flag like “-O2” is set during compilation, the compiler replaces all the occurrences of inline function calls with its code much like a macro expansion.
The use of inline functions avoid the overhead of a function call and still maintains the code readability. An inline function can also be treated as a parameterized macro.
Recent Comments