Programming in C

(Barry) #1

312 Chapter 13 The Preprocessor


The #Operator


If you place a #in front of a parameter in a macro definition, the preprocessor creates a
constant string out of the macro argument when the macro is invoked. For example, the
definition
#define str(x) # x
causes the subsequent invocation
str (testing)
to be expanded into
"testing"
by the preprocessor.The printfcall
printf (str (Programming in C is fun.\n));
is therefore equivalent to
printf ("Programming in C is fun.\n");
The preprocessor literally inserts double quotation marks around the actual macro argu-
ment. Any double quotation marks or backslashes in the argument are preserved by the
preprocessor. So
str ("hello")
produces
"\"hello\""
A more practical example of the use of the #operator might be in the following macro
definition:
#define printint(var) printf (# var " = %i\n", var)
This macro is used to display the value of an integer variable. If countis an integer vari-
able with a value of 100 , the statement
printint (count);
is expanded into
printf ("count" " = %i\n", count);
which, after string concatenation is performed on the two adjacent strings, becomes
printf ("count = %i\n", count);
So the #operator gives you a means to create a character string out of a macro argu-
ment. Incidentally, a space between the #and the parameter name is optional.
Free download pdf