In the following program, I have added an explicit return
statement in func()
, but the compiler gives me the following error:
m.cpp: In
Prior to C++14, the body of a constexpr
function must consist solely of a return
statement: it cannot have any other statements inside it. This works in C++11 :
constexpr int func (int x)
{
return x < 0 ? -x : x;
}
In C++14 and up, what you wrote is legal, as are most other statements.
Source.
C++11's constexpr
functions are more restrictive than that.
From cppreference:
the function body must be either deleted or defaulted or contain only the following:
- null statements (plain semicolons)
static_assert
declarationstypedef
declarations and alias declarations that do not define classes or enumerationsusing
declarationsusing
directives- exactly one
return
statement.
So you can say this instead:
constexpr int func (int x) { return x < 0 ? -x : x; }
static_assert(func(42) == 42, "");
static_assert(func(-42) == 42, "");
int main() {}
Note that this restriction was lifted in C++14.