if constexpr() gives an error in C++17

1.3k views Asked by At

I have read about constexpr in C++17 using this reference link.

Then, I made C++ program to test constexpr :

#include <iostream>

int i = 10;

int func() 
{
    if constexpr (i == 0)
        return 0;
    else if (i > 0)
        return i;
    else
        return -1;
}

int main() 
{
    int ret = func();
    std::cout<<"Ret : "<<ret<<std::endl;
}

But, compiler give an error:

main.cpp: In function 'int func()':
main.cpp:8:25: error: the value of 'i' is not usable in a constant expression
     if constexpr (i == 0)
                         ^
main.cpp:4:5: note: 'int i' is not const
 int i = 10;

Why gives an error?

2

There are 2 answers

3
Sergey Kalinichenko On BEST ANSWER

You misunderstood the meaning of if constexpr. This is not a test for const expression to be performed at runtime, it is a test of a logical expression to be performed at compile time.

The construct is roughly similar to #if of preprocessor, in that the other branch is eliminated, along with code that may otherwise not compile.

This will work:

template<int  i>
int func() 
{
    if constexpr (i == 0)
        return 0;
    else if constexpr (i > 0)
        return i;
    else
        return -1;
}

The compiler knows the value of i at compile time, so depending on its value only one of the three branches is going to remain in the compiled code.

0
max66 On

if constexpr ( condition ) works compile time, so condition must be evaluable compile time.

int i = 0 isn't a constant variable, so i == 0 isn't evaluable compile time.

Try with int const i = 0 or, better, constexpr int i = 0.