The definition of constexpr
functions in C++ is such that the function is guaranteed to be able to produce a constant expression when called such that only constant expressions are used in the evaluation. Whether the evaluation happens during compile-time or at run-time if the result isn't use in a constexpr
isn't specified, though (see also this answer). When passing non-constant expressions to a constexpr
you may not get a constant expression.
Your above code should, however, not compile because i
is not a constant expression which is clearly used by foo()
to produce a result and it is then used as an array dimension. It seems clang implements C-style variable length arrays as it produces the following warning for me:
warning: variable length arrays are a C99 feature [-Wvla-extension]
A better test to see if something is, indeed, a constant expression is to use it to initialize the value of a constexpr
, e.g.:
constexpr int j = foo(i);