i have a constexpr function named access, and i want to access one element from an array:
char const*const foo="foo";
char const*const bar[10]={"bar"};
constexpr int access(char const* c) { return (foo == c); } // this is working
constexpr int access(char const* c) { return (bar[0] == c); } // this isn't
int access(char const* c) { return (bar[0] == c); } // this is also working
i get the error:
error: the value of 'al' is not usable in a constant expression
why can't i access one of the elements from access? or better how do i do it, if it is even possible?
The array needs to be declared
constexpr
, not justconst
.Without that, the expression
bar[0]
performs an lvalue-to-rvalue conversion in order to dereference the array. This disqualifies it from being a constant expression, unless the array isconstexpr
, according to C++11 5.19/2, ninth bullet:(and a couple of other exceptions which don't apply here).