Search code examples
c++c++17constexprif-constexpr

Why does the false branch of "if constexpr" get compiled?


Why is this code giving error while compiling? My knowledge (and also this) of "if constexpr" says the else block shouldn't get compiled.

if constexpr (true) {
    int a = 10;
} else {
    int b = 10
}

The error is:

error: expected ‘,’ or ‘;’ before ‘}’ token

Compiler used: g++ version 7.5.0
While compiling I used -std=c++17 flag.

P.S. The missing ';' is intentional, just to check whether else is being compiled or not.


Solution

  • There are 2 separate, but related issues here.

    Firstly, if constexpr will only conditionally compile a branch within a template. Outside of a template, all branches will be compiled and must be well formed.

    Secondly, even in a template, the discarded branch of an if constexpr can't be ill-formed for all possible instantiations. This is not the case in your code, since:

    int b = 10
    

    is always ill-formed (due to the missing ;).

    So the compiler is correct in giving a compile error. Technically, if the discarded branch is ill-formed for all instantiations, then the compiler is not required to give a compiler error, but the code is still wrong.