Simple constexpr - C26498 warning and C2131 error

Viewed 418

I am trying to learn about const and constexpr and have run into the error C26498 on VS2019. However, my example is almost the same as described here:

constexpr int myInt();
constexpr int getMyValue();
void foo();

int main()
{
    int val1 = myInt(); // C26498 warning (mark variable constexpr)
    const int val2 = myInt();    // C26498 warning (mark variable constexpr)
    constexpr int val3 = myInt();  // C2131 error (expression did not evaluate to a constant)
    foo();
}

constexpr int myInt() { return 1; }

constexpr int getMyValue() { return 1; }

void foo() { constexpr int val0 = getMyValue(); // no C26498 }

Edit: As requested, here is the error list (VS2019):

Warning C26498 - The function 'myInt' is constexpr, mark variable 'val1' constexpr if compile-time evaluation is desired (con.5). line 13

Warning C26498 - The function 'myInt' is constexpr, mark variable 'val2' constexpr if compile-time evaluation is desired (con.5). line 14

Error C2131 - expression did not evaluate to a constant line 15

Message - failure was caused by call of undefined function or one not declared 'constexpr' line 15

I do understand the warnings for val1 and val2, but then when I do use constexpr for val3, I get an error. Why does this throw an error when almost the same code, encapsulated in another function (foo()) doesn't? From my (limited) understanding, can't myInt() also be computed at compile time?

3 Answers

The error occurs because, at the point of use (in the constexpr int val3 = myInt(); line), the compiler does not have a definition of myInt(), and so cannot (safely) deduce a compile-time constant value.

The solution is to put that definition of the myInt function before its use (where you currently have its forward declaration):

constexpr int myInt() { return 1; }

int main()
{
    int val1 = myInt();           // C26498 warning (mark variable constexpr)
    const int val2 = myInt();     // C26498 warning (mark variable constexpr)
    constexpr int val3 = myInt(); // No error or warning!
    return 0;
}

The function must be defined before its call. Most of the time this does not happen because a constexpr function is "implicitly" inline and is defined within the '.h' and so is included in top of the code before compilation.

Please try to declare myInt() before using it (above main() function):

constexpr int myInt();
constexpr int getMyValue();
void foo();

constexpr int myInt() { return 1; }

int main()
{
    int val1 = myInt(); // C26498 warning (mark variable constexpr)
    const int val2 = myInt();    // C26498 warning (mark variable constexpr)
    constexpr int val3 = myInt();  // C2131 error (expression did not evaluate to a constant)

}

constexpr int getMyValue() { return 1; }

void foo() { constexpr int val0 = getMyValue(); // no C26498 }

It worked in my PC (g++ (MinGW.org GCC-8.2.0-5) 8.2.0)

Related