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 the 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 not allowed?

+4
source share
3 answers

Case 1 does not change anything; case 2 changes the variable. It seems pretty obvious to me!

Changing a variable requires that it is not constant, you need to have a mutable state, and the ++x expression changes that state. Since the constexpr function can be evaluated at compile time, there is no "variable" on it, because no code is executed, because we are not yet at run time.

As others have said, C ++ 14 allows constexpr functions constexpr change their local variables, allowing more interesting things, such as for loops. There is still no "variable" there, so the compiler should act as a simplified interpreter at compile time and allow manipulation during compilation with limited forms of the local state. This is a pretty significant change from the more limited C ++ 11 rules.

+8
source

Constant expressions are defined on the last pages of page 5.

As a rough description, they are side-effect-free expressions that can be evaluated at compile time (during translation). The rules associated with them are created taking into account this principle.

+1
source

Your argument is really valid in that, in spirit / technicality, constexpr both x+1 and ++x same. Where x is the local variable of the function. Therefore, in all cases it should be error free .

This problem has now been fixed with C ++ 14. Here is the forked code and compiles with C ++ 14 .

+1
source

Source: https://habr.com/ru/post/1488251/


All Articles