#elseif vs #elif (C/C++ preprocessor)
Asked Answered
K

2

13

I have found that writing

#ifdef ...
#elseif defined(...)
#else
#endif

always results in using either the #ifdef or the #else condition, never the #elseif. But substituting #elif causes it to work as expected based on what's defined. What convoluted purpose, if any, is served by the existence of #elseif? And if none, why doesn't the preprocessor complain?

Maybe this is why for years (decades, really), I've been using ugly #else/#endif blocks, since at least they're reliable!

Krissykrista answered 21/3, 2016 at 17:4 Comment(2)
If the thing after #ifdef is defined, you should see an "Invalid preprocessing directive" error. (Example)Master
#elseif is not part of the C++ language. Only #elif exists: en.cppreference.com/w/cpp/preprocessor/conditionalAliped
I
17

#elseif is not defined. The preprocessor doesn't complain because your #ifdef is false, and the directives within that #ifdef block are not parsed. To illustrate it, this code is valid:

#if 0
#random nonsense
#else
// This must be valid
#endif
Injustice answered 21/3, 2016 at 17:10 Comment(0)
S
-1

I just uncovered in IAR Embedded Workbench for MSP430, v7.11.1, which reports icc430 --version as "IAR C/C++ Compiler V7.11.1.983/W32 for MSP430", that #elseif compiles without error, but does NOT evaluate the same as #elif.

Selfeffacement answered 11/1, 2019 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.