>>> The #define directive can also be used to create macro functions.
>>> A macro function is a symbol created using #defines and that takes an argument much like a function does. The preprocessor will substitute the substitution string for whatever argument its given.
For Example, You can define the macro TWICE AS
#define TWICE(x) ((x) * 2)
and then in your code you write
TWICE(4)
The entire string TWICE(4) will be removed and the value 8 will be substituted!
>>> When the pre compiler sees the 4, it will substitute ((4) * 2), which will then evaluate to 4 * 22 or 8.
>>> A macro can have more than one parameter and each parameter can be used repeatedly in the replacement text. Two common macros are MAX and MIN:
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) > (y) ? (x) : (y))
>>> Note that in a macro function definition the opening parenthesis for the parameter list must immediately follow the macro name with no spaces.
>>> The preprocessor is not as following of white space as in the compiler.
>>> If you were to write
#define MAX (x,y) ((x) > (y) ? (x) : (y))
and then tried to use MAX like this,
int x = 5, y = 7, z;
z = MAX (x,y);
the intermediate code would be
int x = 5, y = 7, z;
z = (x,y) ((x) > (y) ? (x) : (y)) (x,y)
>>> A simple text substitution would be done rather than invoking the macro function.
>>> Thus, the token MAX would have substituted for it (x,y) ((x) > (y) ? (x) : (y)) and then that would be followed by the (x,y) which followed MAX.
>>> By removing the space between MAX and (x,y), however, the intermediate code becomes:
int x = 5, y = 7, z;
z = 7;
I like this
ReplyDelete