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?
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
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.