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?