Search code examples
c++optimizationconstexprif-constexpr

if constexpr vs if with constant


As shown in this question: link, if both of if branches are valid, there's no difference between:

const int foo = 5;
if (foo == 5)
{
    ...
}
else 
{
    ...
}

and

const int foo = 5;
if constexpr (foo == 5)
{
    ...
}
else 
{
    ...
}

in terms of optimization (in both cases the else branch would not be instantiated). So if the expression in vanilla if can be checked at compile time (it involves a const or constexpr) - the optimizations work here as well.

I previously thought that that was the purpose of if constexpr, but I am wrong. So is there a use case of if constexpr other than the case then we may have only one of many if branches valid?


Solution

  • A bit contrived example, but consider this:

    const int foo = 6;
    if (foo == 5)
    {
        some_template_that_fails_to_compile_for_anything_else_than_5<foo>();
    }
    

    This will not compile even though the body of the if will never be executed! Still the compiler has to issue an error. On the other hand, this

    const int foo = 6;
    if constexpr (foo == 5)
    {
        some_template_that_fails_to_compile_for_anything_else_than_5<foo>();
    }
    

    is fine, because the compiler knows at compile time the value of foo and hence does not bother about the body of the if.