Reputation: 950
I've decided to try something. I know macros are evil and should be avoided but wanted to see what's going to happen if I do such a thing.
#include <iostream>
using namespace std;
inline void add(int x, int y) { cout << "Inline: " << x + y << endl; }
#define add(x,y) ( cout << "Macro: " << x + y << endl )
int main()
{
add(3,5);
}
It outputs:
Macro: 8
If I comment out the #define
line inline starts working, and the output turns into Inline: 8
.
My question is, why compiler decides to use macro function instead of inline. Thank you!
I'm using
Linux Mint 18.2
,g++ 5.4.0
, with no parametersg++ -g t2.cpp -o t2
.
Upvotes: 2
Views: 335
Reputation: 37227
A macro comes to effect at the place it is defined, so the inline function is not replaced by the macro, but your call is replaced before compilation. Also note that a macro is not a function, it tells the preprocessor a pattern of replacing texts.
You can run the following command and see the output file (your.i
)
g++ -o your.i -E your.cpp
^
And you'll find the inline function not affected by the macro :)
Option -E
for G++ means "preprocess the source file, but don't compile, don't assemble and don't link".
Upvotes: 2
Reputation: 37520
There is not such thing as "macro function". Compiler (actually preprocessor) just turns main
into
int main()
{
( cout << "Macro: " << 3 + 5 << endl );
}
Upvotes: 2
Reputation:
Macro substitution is performed via the pre-processor before compilation. Thus the compiler never sees add(3,5)
- it only sees the macro expansion.
Upvotes: 5