User's Guide

Example 2
You can use the # and ## operators together:
#include <iostream.h>
#define show_me(arg) int var##arg=arg;\
cout << "var" #arg " is " << var##arg << "\n";
int main()
{
show_me(1);
}
Preprocessing this example yields the following code for the main procedure:
int main()
{
int var1=1; cout << "var" "1" " is " << var1 << "\n";
}
After compiling the code with aCC and running the resulting executable file, you get the following
results:
var1 is 1
Spaces around the # and ## are optional.
In both the # and ## operations, the arguments are substituted as is, without any intermediate
expansion. After these operations are completed, the entire replacement text is rescanned for
further macro expansions.
NOTE: The result of the preprocessor concatenation operator ## must be a _single_ token.
In particular, the use of ## to concatenate strings is redundant and not legal C or C++. For example:
#include
#define concat_token(a, b) a##b
#define concat_string(a, b) a b
int main() {
// Wrong:
printf("%s\n", concat_token("Hello,", " World!"));
// Correct:
printf("%s\n", concat_string("Hello,", " World!"));
// Best: (macro not needed at all!):
printf("%s\n", "Hello," " World!");
}
Using Macros to Define Constants
The most common use of the macro replacement is in defining a constant. In C++ you can also
declare constants using the keyword const. Rather than explicitly putting constant values in a
program, you can name the constants using macros, then use the names in place of the constants.
By changing the definition of the macro, you can more easily change the program:
#define ARRAY_SIZE 1000float x[ARRAY_SIZE];
In this example, the array x is dimensioned using the macro ARRAY_SIZE rather than the constant
1000. Note that expressions that may use the array can also use the macro instead of the actual
constant:
for (i=0; i<<ARRAY_SIZE; ++i) f+=x[i];
Changing the dimension of x means only changing the macro for ARRAY_SIZE. The dimension
changes and so do all of the expressions that make use of the dimension.
Other Macros
Some other common macros used by C programmers include:
Overview of the Preprocessor 123