Macros are built on the #define preprocessor.
Normally a #define would look like:
#define PI 3.142
But, a macro would look like this.
#define SQUARE(x) ( (x)*(x) )
The main difference is that the first example is a constant and the second is an expression. If the macro above was used in some code it may look like this:
#define SQUARE(x) ( (x)*(x) ) main() { int value=3; printf("%d \n", SQUARE(value)); }
After preprocessing the code would become:
main() { int value=3; printf("%d \n", value*value); }
It's generally a good idea to use extra parentheses when using complex macros. Notice that in the above example, the variable "x" is always within it's own set of parentheses. This way, it will be evaluated in whole, before being multiplied. If we used #define SQUARE(x) x*x then SQUARE(a + 3) would result in a + 3 * a + 3 which is evaluated as 3*a + a + 3 and NOT as (a + 3) * (a + 3)
Also, the entire macro is surrounded by parentheses, to prevent it from being contaminated by other code. If you're not careful, you run the risk of having the compiler misinterpret your code.
The # and ## operators are used with the #define macro. Using # causes the first argument after the # to be returned as a string in quotes. Using ## concatenates what's before the ## with what's after it.
Example code:
For example, the command
#define to_string( s ) # s
will make the compiler turn this command
cout << to_string( Hello World! ) << endl;
into
cout << "Hello World!" << endl;
Here is an example of the ## command:
#define concatenate( x, y ) x ## y
...
int xy = 10;
...
This code will make the compiler turn
cout << concatenate( x, y ) << endl;
into
cout << xy << endl;
which will, of course, display '10' to standard output.
Top | Master Index | Keywords | Functions |