Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if defined(token) && token == ... - is this syntax legal?

assuming I have such code:

#if defined(SOMEDEF) && SOMEDEF >= 5
  // ...
#endif

Basically, SOMEDEF may not be defined but used in suppressed branch of operator &&. GCC accepts this code, but is it legal according to standard? Do all compilers support this?

like image 302
Andrei R. Avatar asked Dec 31 '25 15:12

Andrei R.


2 Answers

Strictly, it depends.

#if defined(SOMEDEF) && SOMEDEF >= 5

Is legal if one of the following is true:

  • SOMEDEF is defined, and the macro expansion of SOMEDEF is such that the above is a valid expression.
  • SOMEDEF is not defined. In this case, SOMEDEF >= 5 is still a valid expression. Note that after macro replacement (and defined operator evaluation), any identifiers (except true/false) that are not defined are replaced with 0; 0 >= 5 is a valid subexpression.

For example, this is not valid:

#define SOMEDEF 0(0)
#if defined(SOMEDEF) && SOMEDEF >= 5

...because 0(0) >= 5 is not a valid subexpression.

for instance, `#if defined(__has_cpp_attribute) && __has_cpp_attribute(deprecated)` doesn't work

You mean to say, this doesn't work when __has_cpp_attribute is not defined. The same thing happens in this case; 0(0) is not a valid subexpression.

like image 129
H Walters Avatar answered Jan 03 '26 04:01

H Walters


Yes, the code you have in your question is valid. In fact, you don't even need to check if SOMEDEF is defined. It will be assumed to be 0 if it isn't. So, this is functionally equivalent:

#if SOMEDEF >= 5
  // ...
#endif
like image 44
Ken Thomases Avatar answered Jan 03 '26 06:01

Ken Thomases



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!