Is the size of an array determined at compile time?

后端 未结 3 1898
长情又很酷
长情又很酷 2021-01-19 19:25

When I was reading about the array initialization in this tutorial. I found out this note.

type name [elements];

NOTE: The e

3条回答
  •  醉梦人生
    2021-01-19 19:55

    The declaration T a[N] requires that N be a converted constant expression.

    Converted constant expression is an expression implicitly converted to prvalue of type T, where the converted expression is a core constant expression. If the literal constant expression has class type, it is contextually implicitly converted to the expected integral or unscoped enumeration type with a constexpr user-defined conversion function.

    An int literal such as 5 is a prvalue, so can be used in the declaration T a[5], but an lvalue, for example int n = 5 cannot be used in the declaration T a[n], unless the lvalue under-goes an implicit lvalue-to-rvalue conversion where the lvalue:

    a) has integral or enumeration type, is non-volatile const, and is initialized with a constant expression, or an array of such (including a string literal)

    b) has literal type and refers to a non-volatile object defined with constexpr or to its non-mutable subobject

    c) has literal type and refers to a non-volatile temporary, initialized with a constant expression

    Therefore the following are valid:

    const int n = 5; 
    int a[n]; 
    constexpr int n = 5; 
    int a[n];
    

提交回复
热议问题