0

I read the book "C++ Concurrency in Action, 2nd Edition" (from Anthony Williams), and I'm not sure of one sentence in appendix A.4.1 :

"But that's about all you can do in C++11 - a constexpr function can only call other constexpr functions. In C++14, this restriction is lifted, and you can do almost anything in a constexpr function, provided it doesn't modify any objects with non local scope."

In this thread from 2015, someone also states that it is not allowed to modify non-local objects in a constexpr function :

If you want to write a function that isn't allowed to modify any non-local variables at all, you can declare it constexpr, although that also imposes additional restrictions.

This statement seems contradicted by this SO thread. In it, there is a a constexpr function that modify a variable from outer scope by passing by reference, the code compiles and somebody cites a paper which says that since c++14 :

A constant expression may still have side-effects which are local to the evaluation and its result.

So now I'm confused : Is it possible (and authorized by the standard) since c++14 to modify objects with non-local scope in constexpr function ?

2
  • 1
    None of the examples in that thread have a constexpr function modify a global variable, but rather a local variable within another constexpr function. In any case, constexp doesn't mean "always evaluated at compile time" (there's consteval for that), it means "can be evaluated at compile time, and must be evaluated at compile time when used in a context where a compile-time constant is required". See if this example proves illuminating. Commented Dec 18, 2024 at 2:49
  • ok thank you, indeed your example is instructive and I with your explanation I understand now. If you want to add an answer in the same tone I will accept it. Commented Dec 18, 2024 at 10:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.