f78 Stringification Contents|Index|Previous|Next
 

Stringification 

Stringification means turning a code fragment into a string constant whose contents are the text for the code fragment. For example, stringifying foo (z) results in "foo (z)".

In the C preprocessor, stringification is an option available when macro arguments are substituted into the macro definition. In the body of the definition, when an argument name appears, the character # before the name specifies stringification of the corresponding actual argument when it is substituted at that point in the definition. The same argument may be substituted in other places in the definition without stringification if the argument name appears in those places with no #.

What follows is an example of a macro definition that uses stringification.

The actual argument for EXP is substituted once as given, into the if statement, and once as stringified, into the argument to fprintf. The do and while (0) are a work-around to make it possible to write WARN_IF (arg);, c55 which the resemblance of WARN_IF to a function would make C programmers want to do; see Swallowing the semicolon.

The stringification feature is limited to transforming one macro argument into one string constant; there is no way to combine the argument with other text and then stringify it all together. The previous example shows how an equivalent result can be obtained in ANSI Standard C using the feature that adjacent string constants are concatenated as one string constant. The preprocessor stringifies the actual value of EXP into a separate string constant, resulting in text like the following output.

The C compiler then sees three consecutive string constants and concatenates them into one, producing, effectively, the following output. Stringification in C involves more than putting doublequote characters around the fragment; it is necessary to put backslashes in front of all doublequote characters, and all backslashes in string and character constants, in order to get a valid C string constant with the proper contents. Thus, stringifying p="foo\n"; results in "p=\"foo\\n\";". However, backslashes that are not inside of string or character constants are not duplicated: \n by itself stringifies to "\n".

Whitespace (including comments) in the text being stringified is handled according to precise rules. All leading and trailing whitespace is ignored. Any sequence of whitespace in the middle of the text is converted to a single space in the stringified result. 0