I got this example from §5.19/2 in N4140:
constexpr int incr(int &n) {
return ++n;
}
As far as I can tell, this is not a constexp
As far as I can tell, this is not a
constexpr
function.
Why do you say that? The example from §5.19/2 reads:
constexpr int g(int k) {
constexpr int x = incr(k); // error: incr(k) is not a core constant
// expression because lifetime of k
// began outside the expression incr(k)
return x;
}
incr(k)
not being a core constant expression does not mean incr
cannot not be a constexpr function.
Under C++14's constexpr rules, it is possible to use incr
in a constexpr context, for example:
constexpr int incr(int& n) {
return ++n;
}
constexpr int foo() {
int n = 0;
incr(n);
return n;
}
Unless it's downright impossible for the body of the function to be constexpr
(for example, calling a non-constexpr function unconditionally), the compiler has no reason to produce an error at the point of definition.
A constexpr function may even contain paths/branches in the body which would not be constexpr. As long as they are never taken in a constexpr context, you will not get an error. For example:
constexpr int maybe_constexpr(bool choice, const int& a, const int& b) {
return choice ? a : b;
}
constexpr int a = 0;
int b = 1;
static_assert(maybe_constexpr(true, a, b) == 0, "!");
live example