Google

Macro vs. Inline function in C++

Written on:May 13, 2013
Comments are closed




Macro vs. Inline function in C++

Functions considerably increase the speed of the program, when it is likely to be called many number of times.  But, if the function is small in size, then it may be defined as inline function which greatly reduces the function calling overheads.  Whenever an inline function is called, the function is inserted in the code itself rather than calling it, as is the case with normal functions.  This insertion is performed during compilation time.  Inline functions are declared like normal functions except that the function precedes with the keyword inline.

 

However, it should be noted that it is up to the wish of the compiler to make a function inline or not, even after inline specification has been given.  Also the inlining procedure will not follow if a function contains static variable or is recursive.  If a function has looping or conditional construct, and it also return value, then the inlining won’t function.


 

Macro is a preprocessor directive.  It is not really a function.  So some overheads are involved in error checking during compilation time.  When a constant is associated with a user defined symbol, that could be used in place of constant, the characters making up the constant are assigned not the numeric value of the constants.  All macros can occupy more than one line but they can not include a newline.  Macros can take arguments too.  The advantages of macros vs. functions depend on the situation.  C++ provides its own facility to define functions as inline, which have same working as that of macros, but, since they are functions, so the compiler checks for the possible errors very easily.  Further, it is upto the compiler whether to make a function inline or not, but macros, without memory consideration are expanded.  Thus in C++, inline functions prove to be much useful then macros.

Sorry, the comment form is closed at this time.