Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rules for constexpr functions

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?

like image 912
Alok Save Avatar asked Dec 20 '22 03:12

Alok Save


1 Answers

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.

like image 107
Jonathan Wakely Avatar answered Dec 24 '22 02:12

Jonathan Wakely