Search code examples
cunixfortranpreprocessor

Do preprocessors expand macros surrounded by quotation marks?


Do common preprocessors like cpp and fpp expand macros surrounded by a pair of quotation marks?

I tried the following code using both cpp and fpp, it seems that the macros within quotation marks are not expanded. However, I did not find this rule in any documentation about cpp or fpp. Could anyone kindly direct me to some documentation so that I can be sure about this behavior? Thanks.

#define X Y
X
"X"
'X'

Solution

  • Do common preprocessors like cpp and fpp expand macros surrounded by a pair of quotation marks?

    The C language specification describes the behavior of conforming C preprocessors. The actual standards for C are not freely available, but you can get copies of late drafts. For C18, for example, you could refer to N2176. In particular, you should have a look at sections 5.1.1.2 and 6.10.3. Of particular relevance is footnote 173 in section 6.10.3:

    Since, by macro-replacement time, all character constants and string literals are preprocessing tokens, not sequences possibly containing identifier-like subsequences (see 5.1.1.2, translation phases), they are never scanned for macro names or parameters.

    (Substantially the same text appears in earlier versions of the standard, too.)

    The bottom line for C, then, is that no, a conforming C preprocessor does not perform macro replacement on the contents of string literals or character constants.


    The situation for Fortran is less clear cut, because the Fortran language specification does not define preprocessing facilities. There is an include statement built in to the language itself, but Fortran practitioners generally would not consider its use to involve preprocessing. Fortran source code rarely relies on preprocessing features such as macro expansion or conditional compilation.

    Some Fortran implementations nevertheless do provide a preprocessing facility, sometimes available as a standalone program named fpp. You would need to consult the documentation of your specific fpp for details, but generally these are adaptations of the C preprocessor to Fortran syntax. As such, no, I would not expect a Fortran preprocessor to perform macro expansion on the contents of character literals. I am not aware of any implementations that defy my expectations in that regard.