Can comments be created in macro definition by "/##/"?

Viewed 34

Assuming that the IDE defines macro NDEBUG in Release build. Is it possible to use the following preprocessor instructions to print debug information in Debug build but not in Release build by using the marco PRINT?

#ifdef NDEBUG
#define PRINT /##/
#else
#define PRINT printf
#endif
1 Answers

No, because replacement of comments with spaces occurs before macro replacement in C’s translation phases.

C 2018 5.1.1.2 1 specifies the precedence of syntax rules in translation. Phase 3 is:

The source file is decomposed into preprocessing tokens and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment. Each comment is replaced by one space character…

Phase 4 is:

Preprocessing directives are executed, macro invocations are expanded…

Interestingly, earlier phases can be invoked by later phases, but this only occurs for processing #include directives; the specification for phase 4 continues:

… A #include preprocessing directive causes the named header or source file to be processed from phase 1 through phase 4, recursively…

Further, pasting / with / to produce // has undefined behavior, because // is not a preprocessing token and C 2018 6.10.3 3 says, of pasting with the ## operator:

… If the result is not a valid preprocessing token, the behavior is undefined…

(Preprocessing tokens are specified in C 2018 6.4 1, and the relevant category there would be punctuator, which includes characters and character combinations such as [, ], +, ++, /, +=, /=, >>=, and so on but does not include //.)

A typical means of accomplishing the goal of printing in a debug build but not a non-debug build is to define a function-like macro that is replaced by nothing in non-debug builds:

#if defined NDEBUG
    #define PRINT(...)
#else
    #define PRINT(...) printf(__VA_ARGS__)
#endif
Related