2

Possible Duplicate:
Can a string literal be subscripted in a constant expression?

If I subscript a string literal, is the result a compile-time constant? In other words, is the following code valid?

constexpr char x = "a"[0];

GCC 4.7 says it is, but what does the standard have to say on this matter?

For the curious: I can't just write 'a', because the string literal is the result of the stringizing operator. Some compilers do have a charizing operator, but it's only an extension.

Community
  • 1
  • 1

1 Answers1

3

I think you're looking at 5.19 [expr.const]:

2 - A conditional-expression is a core constant expression unless it involves one of the following [...]

  • an lvalue-to-rvalue conversion (4.1) unless it is applied to
    • a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression [ Note: a string literal (2.14.5) corresponds to an array of such objects. —end note ] [...]

So the result of a string literal subscript operation may be converted to an rvalue in a core constant expression.

This is useful when defining constexpr operators for user-defined literals and user-defined string literals, although the variadic form can be more workable in some cases.

ecatmur
  • 152,476
  • 27
  • 293
  • 366