Macros with arguments
We can also write macros that accept arguments. Here's an example of a macro with an argument:
#define println(X) cout << X << endl;
What this macro will do is every time println("Some value")
is encountered in the code, the code on the right-hand side (cout << "Some value" << endl
) will be copied and pasted on the console. Notice how the argument between the brackets is copied in the place of X
. Say we had the following line of code:
println( "Hello there" )
This will be replaced by the following statement:
cout << "Hello there" << endl;
Macros with arguments are exactly like very short functions. Macros cannot contain any newline characters in them.
Advice – use inline functions instead of macros with arguments
You have to know about how macros with arguments work because you will encounter them in C++ code a lot. Whenever possible, however, many C++ programmers prefer to use inline functions...