user997112
user997112

Reputation: 30615

How does #define know when to stop looking?

I use a macro in C++ to switch between compiling logging or not:

#define MAYBE_LOG(msg) 
#ifdef PRINT_MSGS 
ALWAYS_LOG(msg) 
#endif

How does the #define know where the ending is? The #endif refers to the #ifdef, not the #define.

Upvotes: 1

Views: 97

Answers (2)

Pete Becker
Pete Becker

Reputation: 76315

The code in the question does two separate things: it defines a macro named MAYBE_LOG with no body and, if PRINT_MSGS is defined, it uses a macro named ALWAYS_LOG. If that's not what it's supposed to do, then, yes, it needs to be changed. Since the question doesn't say what the code is supposed to do, this is just a guess:

#ifdef PRINT_MSGS
#define MAYBE_LOG(msg) ALWAYS_LOG(msg)
#else
#define MAYBE_LOG(msg)
#endif

The reason for doing it this way (and not using \ on each line to extend the macro definition is that you can't put #if conditions inside the definition of a macro.

Upvotes: 2

Jarod42
Jarod42

Reputation: 217418

#define ends at end of the line (which might be extended with final \)

Upvotes: 4

Related Questions