The # Operator
If you place a # in front of a parameter in a macro definition, the preprocessor creates
a constant C-style 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 printf call
printf (str (Programming in Objective-C is fun.\n));
is therefore equivalent toprintf ( ”Programming in Objective-C is fun.\n ”);
The preprocessor inserts double quotation marks around the actual macro argument.
The preprocessor preserves any double quotation marks or backslashes in the argument. Sostr (“hello”)
produces”\”hello\ ””
A more practical example 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 integervariable with a value of 100 , the statement
printint (count);is expanded into this:
printf ( ”count”“ = %i\n ”, count);The compiler concatenates two adjacent literal strings to make a single string.
There-fore, after concatenation is performed on the two adjacent strings,
the statement becomes the following:
printf ( ”count = %i\n”, count);
The ##Operator
The ##operator is used in macro definitions to join two tokens. It is preceded (or fol-lowed)
by the name of a parameter to the macro.The preprocessor takes the actual argu-ment to
the macro that is supplied when the macro is invoked and creates a single token out of
that argument and whatever token follows (or precedes) the ##.
Suppose, for example, that you have a list of variables x1through x100.You can write a
macro called printx that simply takes as its argument an integer value 1–100 and displays
the corresponding x variable, as shown here:
#define printx(n) printf (”%i\n”, x ## n)
The portion of the define that reads
x ## n
says to use the tokens that occur before and after the ##(the letter x and the argument n,
respectively) and make a single token out of them. So the call
printx (20);
is expanded into the following:
printf ( ”%i\n”, x20);
The printx macro can even use the previously defined printint macro to get the
variable name as well as its value displayed:
#define printx(n) printint(x ## n)
The invocation
printx (10);
first expands into
printint (x10);
and then into
printf ( ”x10 ”“ = %i\n ”, x10);
and finally into the following:
printf ( ”x10 = %i\n”, x10);