The unary operator # is commonly called the stringify operator (or sometimes the stringizing operator) because it converts a macro argument into a string. The operand of # must be a parameter in a macro replacement text. When a parameter name appears in the replacement text with a prefixed # character, the preprocessor places the corresponding argument in double quotation marks, forming a string literal. All characters in the argument value itself remain unchanged, with the following exceptions:
-
Any sequence of whitespace characters between tokens in the argument value is replaced with a single space character.
-
A backslash character (\) is prefixed to each double quotation mark character (") in the argument.
-
A backslash character is also prefixed to each existing backslash that occurs in a character constant or string literal in the argument, unless the existing backslash character introduces a universal character name.
The following example illustrates how you might use the # operator to make a single macro argument work both as a string and as an arithmetic expression in the replacement text:
#define printDBL( exp ) printf( #exp " = %f ", exp ) printDBL( 4 * atan(1.0)); // atan( ) is declared in math.h.
The macro call in the last line expands to this statement:
printf( "4 * atan(1.0)" " = %f ", 4 * atan(1.0));
Because the compiler merges adjacent string literals, this code is equivalent to the following:
printf( "4 * atan(1.0) = %f ", 4 * atan(1.0));
That statement would generate the following console output:
4 * atan(1.0) = 3.141593
Source: C in a Nutshell - O'Reilly Media
No comments:
Post a Comment