#ifdef with multiple tokens, is this legal?

Today I came across some C ++ code that contains a #ifdef clause like this:

#ifdef DISABLE_UNTIL OTHER_CODE_IS_READY foo(); #endif 

Note the space between "DISABLE_UNTIL" and "OTHER_CODE_IS_READY". Essentially, there are two tokens in the #ifdef line.

My question is, is this legal C ++ code? (g ++ compiles it without any errors and apparently just ignores the second token). And if this is legal, should a second token work?

+6
source share
2 answers

[C++11 16.1] , [C++11 16.5] and, by the way, [C99 6.10.1/4] all say that this is not true.

if-groups:
# if expression constant newline group opt
# ifdef identifier new-line group opt
# ifndef identifier new-line group opt

Only one identifier is allowed.

GCC's own documentation agrees .

My own tests assume that only the first identifier is accepted, and the second is simply discarded; this may be a simplification of implementation, but the standard requires diagnostics here, so you should see this when using the -pedantic flag of at least & dagger; .

 #include <iostream> using namespace std; #define A #define B int main() { #ifdef A std::cout << "a "; #endif #ifdef B std::cout << "b "; #endif #ifdef C std::cout << "c "; #endif #ifdef BC std::cout << "bc "; #endif #ifdef CB std::cout << "cb "; #endif return 0; } // Output: "ab bc" // Note: "cb" *not* output 

& dagger; The Coliru GCC installation emits with or without -pedantic .

+6
source

The syntax you posted is not legal, and the intended meaning is unclear.

Depending on what you hope to accomplish, can you use || or && to combine them?
(of course, if it is someone else's code, I would just reject it as inappropriate / unsuitable)

 #if defined(DISABLE_UNTIL) || defined(OTHER_CODE_IS_READY) foo(); #endif 
+10
source

Source: https://habr.com/ru/post/955784/


All Articles