Tuesday, July 28, 2009

What is difference between macro and inline function in c++?

what are the different conditions in which inline function and macro works differently?

What is difference between macro and inline function in c++?
The difference is that "inline functions" are part of the language, whereas "macro functions" are really compiler directives.





As they are compiler directives, macros are handled at or before compile time by the compiler. Inline code, on the other hand, is compiled as it is written. According to the Wikipedia article about inline functions, Bjarne Stroustrup, creator of C++, recommends that macros should not be used very much.





Often times, reliance on macros is considered bad coding practice and they may be less efficient -- they are definitely less intuitive. Generally, marcos are accepted in cross platform hacks, translating certain system dependent code to what it should be on a particular system (in that case, usually a particular system, like POSIX, is coded for, and hacks are used to let the code properly compile for Windows and other non-POSIX systems).
Reply:The main difference is that macros are expanded by the preprocessor and inline functions are parsed by the compiler.





Also, inline functions still follow all the type safety stuff (which are enforced on normal functions).





Another thing to keep in mind is that macros are expanded at pre-compile time, so you cannot use them for debugging. For inline functions, however, this is not the case.





Finally, be aware that arguments in a macro can be evaluated more than once (this could cause unexpected results, especially if you are doing something like an increment on a variable and trying to do it as part of the arguments).


No comments:

Post a Comment