x[0] == 1 constant expression in C++11 when x is const int[]?

后端 未结 2 1216
梦谈多话
梦谈多话 2020-12-29 05:57

Is the following C++11 program ill-formed?

const int x[] = {1,2,3};

static_assert(x[0] == 1, \"yay\");

int main() {}

gcc and clang seem t

2条回答
  •  忘掉有多难
    2020-12-29 06:30

    In 5.19:

    A [...]expression is a constant expression unless it involves one of the following [...]:

    • an lvalue-to-rvalue conversion (4.1) unless it is applied to

      • a glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression, or
      • a glvalue of literal type that refers to a non-volatile object defined with constexpr, or that refers to a sub-object of such an object, or
      • a glvalue of literal type that refers to a non-volatile temporary object initialized with a constant expression

    Putting it plainly, lvalue-to-rvalue conversion can only be done in constant expressions if:

    • a constant integral (or enum) declaration initialized with a constant: const int x = 3;.
    • a declaration with constexpr: constexpr int x[] = {1,2,3};.
    • a temporary object initialized with a constant expression...

    Your example does include lvalue-to-rvalue conversion, but has none of these exceptions, so x is not a constant expression. If, however, you change it to:

    constexpr int x[] = {1,2,3};
    
    static_assert(x[0] == 1, "yay");
    
    int main() {}
    

    Then all is well.

提交回复
热议问题