c++c-preprocessorpreprocessorpreprocessor-directive

Is it legal to use #elif with #ifdef?


A simple question that Google doesn't help me with. Is it legal in C++ to use #elif clause in the context of #ifdef? It seems to compile and work as expected with all the major compilers in the c++11 mode (MSVC 2015/2017, clang, GCC), but I'm not certain whether it is standard-compliant.


Solution

  • Yes, the grammar allows an #elif after preceding, matching #if, #ifdef or #ifndef:

    if-section:
        if-group elif-groupsopt else-groupopt endif-line

    if-group:
        # if constant-expression new-line groupopt
        # ifdef identifier new-line groupopt
        # ifndef identifier new-line groupopt

    Note that #ifdef X is just short for #if defined(X), and #ifndef X for #if ! defined(X).