Do “#define” and inline behave the same?
No they dont!
There are a number of differences between a macro and a inline function.
- No of times of Evaluation
Expressions passed as arguments to inline functions are evaluated once.
In some cases, expressions passed as arguments to macros can be evaluated more than once. Every time you use an argument in a macro, that argument is evaluated.
A Code sample:
#define max(a,b) (a>b?a:b) int main() { int a = 0; int b = 1; int c = max(a++, b++); cout << a << endl << b << endl; return 0; }
The intention probably was to print 1 and 2, but macro expands to:
int c = a++ > b++ ? a++ : b++;
b gets incremented twice, and the program prints 1 and 3.
- Who evaluates them
Inline functions are evaluated by the compiler while Macros are evaluated at pre-compilation by precompiler.
- Type checking
Inline functions follow all the protocols of type safety enforced on normal functions. Argument types are checked, and necessary conversions are performed correctly. The compiler performs return type checking, function signature before putting inline function into symbol table.
They can be overloaded to perform the right kind of operation for the right kind of data.
Macros are more error prone as compared to inline functions. the The parameters are not typed (the macro works for any objects of arithmetic type). No error checking is done during compilation.
A Code Sample:
#define MAX(a, b) ((a < b) ? b : a) int main( void) { cout << "Maximum of 10 and 20 is " << MAX("20", "10") << endl; return 0; }
One can pass strings to a macro that does some integer arithmetic and a macro won't complain!
- Suggestion or Command?
Inline is just a suggestion to the compiler. It is the compiler’s decision whether to expand the function inline or not.
Macros will always be expanded.
- How about Debugging?
Inline functions can be debugged easily because you can put a break point at the inline function definition and step into the method for debugging step by step.
Macros can not be used for debugging as they are expanded at pre-compile time.
2 * ROUND_DOWN(178, 32)will make things not work anymore. Use#define ROUND_DOWN(a,b) ((a)-(a)%(b))instead (note the extra parentheses). Conclusion: won't behave the same anyway.ROUND_DOWN(x++, y)with your macro and see what happens.