3

Reading through the constexpr specifier documentation on cppreference, I've noticed that the standard says the following:

[...] the function body [of constexpr function] must be either deleted or defaulted or contain only the following: [...] if the function is not a constructor, exactly one return statement.

What is the motivation behind imposing such a requirement? Although I can understand that this could potentially lead to a simpler implementation of the constexpr interpreter, I do not see the reason why this limitation had to be imposed.

Both clang 15.0.0 and gcc 12.2 compile constexpr functions with multiple return statements with no problem. Am I reading the standard wrong or was this just some "obsolete" decision that is no longer being followed?

jsfpdn
  • 73
  • 1
  • 6

1 Answers1

3

It used to be a restriction when constexpr was introduced to the language in C++11. Basically, back then, constexpr functions could only consist of a single return statement (like a simple getter function). The scope of constexpr has been extended since then and it's now much more capable than before. I guess the restrictions were due to

  1. it was a new feature back then, so the committee was conservative in its scope, and
  2. in a constexpr context, UB is not allowed, which means the compiler has to prove that you're not invoking UB. I assume this was easier to implement from a compiler vendor perspective.
Timo
  • 9,269
  • 2
  • 28
  • 58
  • 2
    I do not think that the second point matters. Even with just one return statement C++11 `constexpr` functions are already Turing-complete and can evaluate basically arbitrary complex expressions. The really tricky UB cases (e.g. the ones related to indeterminate/unspecified order of evaluation) are still open issues and would have been there with a single return statement as well. – user17732522 Feb 27 '23 at 16:11