Friday, July 31, 2009

Is Macro concept in C language and Inline function in C++ are same?

If not what is the important difference and which one is efficent

Is Macro concept in C language and Inline function in C++ are same?
No. Macros work both in C and C++ and they are evaluated and expanded by the prepocessor before compiling. Macros are mostly a tool to make code easier to write for programmers. They don't really affect the way the program executes





Inlining functions on the otherhand is used to increase performance. You can manually inline functions using the "inline" keyword or the compiler will automatically do it for you too depending on your compiler settings.





Inlining moves the code for a function into the code that called the function. Since calling a function has some performance overhead moving the code into the calling function can result in faster performance. Realize that the code for an inlined function gets copied to every place the function is called, therefore the code size gets bigger. In general good functions to inline are short and are called frequently in tight loops.
Reply:No, they are different. A macro will always do copy + paste + substitution, for an inline function the compiler will decide if and when it will do copy + paste + substitution.
Reply:I agree with tykyle. I also add that macros are potentially dangerous. First, they can have side effects that are not always obvious. Second, you can't really debug into them, because they aren't really there. The compiler doesn't know about them, only the preprocessor. So (for c++) unless the macro is *really* simple, I'd be inclined to use inline functions.





I'd also add (with respect to use in tight loops) that the compiler always has the opportunity to optimize. True for both macros and inline.





BTW, the business about the compiler knowing about the code (vs the preprocessor only) is why #define statements are deprecated in c++ (as in #define pi 3.1415) vs const statements. Same thing.


No comments:

Post a Comment