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?

3
  • cppreference isn't the standard? Commented Feb 27, 2023 at 16:08
  • 8
    That part has a note saying (until C++14), so in newer standards this limitation doesn't exist. Commented Feb 27, 2023 at 16:09
  • 1
    @IlCapitano is correct, the note "until c++14" is bound to the whole list of bullet points, not only to the one bullet point you mentioned. Commented Feb 27, 2023 at 17:03

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.