The # (single number sign) operator converts a parameter
of a function-like macro into a character string literal. For example,
if macro ABC is defined using the following directive:
#define ABC(x) #x
all subsequent invocations of the macro ABC would be expanded
into a character string literal containing the argument passed to
ABC. For example:
Invocation
| Result of Macro Expansion
|
ABC(1)
| "1"
|
ABC(Hello there)
| "Hello there"
|
The # operator should not be confused with the null
directive.
Use the # operator in a function-like macro definition
according to the following rules:
- A parameter following # operator in a function- like
macro is converted into a character string literal containing the argument
passed to the macro.
- White-space characters that appear before or after the argument passed to
the macro are deleted.
- Multiple white-space characters imbedded within the argument passed to the
macro are replaced by a single space character.
- If the argument passed to the macro contains a string literal and if a
\ (backslash) character appears within the literal, a second
\ character is inserted before the original
\ when the macro is expanded.
- If the argument passed to the macro contains a " (double
quotation mark) character, a \ character is inserted before
the " when the macro is expanded.
- The conversion of an argument into a string literal occurs before macro
expansion on that argument.
- If more than one ## operator or
# operator appears in the replacement list of a macro
definition, the order of evaluation of the operators is not defined.
- If the result of the macro expansion is not a valid character string
literal, the behavior is undefined.
Example of the # Operator
The following examples demonstrate the use of the #
operator:
#define STR(x) #x
#define XSTR(x) STR(x)
#define ONE 1
Invocation
| Result of Macro Expansion
|
STR(\n "\n" '\n')
| "\n \"\\n\"
'\\n'"
|
STR(ONE)
| "ONE"
|
XSTR(ONE)
| "1"
|
XSTR("hello")
| "\"hello\""
|
Related References
