12/3/2016
StringificationTheCPreprocessor
Next:Concatenation,Previous:MacroArguments,Up:Macros
3.4Stringification
[Link]
stringconstants,butyoucanusethe#[Link]
leading#,thepreprocessorreplacesitwiththeliteraltextoftheactualargument,convertedtoastring
[Link],[Link]
stringification.
[Link],youcan
[Link]
[Link]
longstring.
Hereisanexampleofamacrodefinitionthatusesstringification:
#defineWARN_IF(EXP)\
do{if(EXP)\
fprintf(stderr,"Warning:"#EXP"\n");}\
while(0)
WARN_IF(x==0);
==>do{if(x==0)
fprintf(stderr,"Warning:""x==0""\n");}while(0);
TheargumentforEXPissubstitutedonce,asis,intotheifstatement,andonce,stringified,intotheargumentto
[Link],itwouldbeexpandedintheifstatement,butnotinthestring.
Thedoandwhile(0)areakludgetomakeitpossibletowriteWARN_IF(arg);,whichtheresemblanceof
WARN_IFtoafunctionwouldmakeCprogrammerswanttodoseeSwallowingtheSemicolon.
[Link]
backslashescapesthequotessurroundingembeddedstringconstants,andallbackslasheswithinstringand
characterconstants,[Link],stringifying
p="foo\n";resultsin"p=\"foo\\n\";".However,backslashesthatarenotinsidestringorcharacter
constantsarenotduplicated:\nbyitselfstringifiesto"\n".
[Link]
[Link]
longbeforestringificationhappens,sotheyneverappearinstringifiedtext.
Thereisnowaytoconvertamacroargumentintoacharacterconstant.
Ifyouwanttostringifytheresultofexpansionofamacroargument,youhavetousetwolevelsofmacros.
#definexstr(s)str(s)
#definestr(s)#s
#definefoo4
str(foo)
==>"foo"
xstr(foo)
==>xstr(4)
==>str(4)
==>"4"
[Link]
1/2
12/3/2016
StringificationTheCPreprocessor
sisstringifiedwhenitisusedinstr,[Link],so
itiscompletelymacroexpandedbeforexstritselfisexpanded(seeArgumentPrescan).Therefore,bythetime
strgetstoitsargument,ithasalreadybeenmacroexpanded.
[Link]
2/2