In the following example:
//Case 1
constexpr int doSomethingMore(int x)
{
return x + 1;
}
//Case 2
constexpr int doSomething(int x)
{
return ++x;
}
int main()
{}
Output:
prog.cpp: In function ‘constexpr int doSomething(int)’:
prog.cpp:12:1: error: expression ‘++ x’ is not a constant-expression
Why is Case 1 allowed but Case 2 is not allowed?
Case 1 doesn't modify anything, case 2 modifies a variable. Seems pretty obvious to me!
Modifying a variable requires it to not be constant, you need to have mutable state and the expression ++x
modifies that state. Since a constexpr
function can be evaluated at compile-time there isn't really any "variable" there to modify, because no code is executing, because we're not at run-time yet.
As others have said, C++14 allows constexpr
functions to modify their local variables, allowing more interesting things like for
loops. There still isn't really a "variable" there, so the compiler is required to act as a simplified interpreter at compile-time and allow limited forms of local state to be manipulated at compile-time. That's quite a significant change from the far more limited C++11 rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With