3

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?

3
  • Does it work? or not? Commented Sep 18, 2013 at 17:25
  • @MikeSeymour ok I don't know C++ Should I delete comment? Commented Sep 18, 2013 at 17:26
  • @GrijeshChauhan sorry, no it's not working. my approach is working without constexpr. Commented Sep 18, 2013 at 17:27

1 Answer 1

9

The array needs to be declared constexpr, not just const.

constexpr char const* bar[10]={"bar"};

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 is constexpr, according to C++11 5.19/2, ninth bullet:

an lvalue-to-rvalue conversion unless it is applied to

  • a glvalue of literal type that refers to a non-volatile object defined with constexpr

(and a couple of other exceptions which don't apply here).

Sign up to request clarification or add additional context in comments.

4 Comments

Now the interesting question is, why does it work for the non-array version even if that is just const but not constexpr?
@us2012: I'm not sure of the exact rules; I think you can use const values (including pointers like foo), but not the results of expressions (like bar[0]) unless all the subexpressions are constexpr. Or something.
@us2012: I think I've found the relevant rule now.
So then how the array element is accessed - this is so hilarious.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.