Can an array be declared with a size that is a const variable not a constexpr?

前端 未结 1 709
心在旅途
心在旅途 2020-12-06 13:06

Is this C++ code correct?

const size_t tabsize = 50;
int tab[tabsize];

The problem is that I\'ve already seen numerous conflicting opinions

相关标签:
1条回答
  • 2020-12-06 13:58

    In C++ constant integers are treated differently than other constant types. If they are initialized with a compile-time constant expression they can be used in a compile time expression. This was done (in the beginning of C++, when constexpr didn't exist) so that array size could be a const int instead of #defined (like you were forced in C):

    (Assume no VLA extensions)

    const int s = 10;
    int a[s];          // OK in C++
    
    const int s2 = read(); // assume `read` gets a value at run-time
    int a2[s2];       // Not OK
    
    int x = 10;
    const int s3 = x;
    int a3[s3];       // Not OK
    

    So the answer is yes, you can use a const integer variable as the size of an array if it was initialized by a compile time constant expression


    This is my answer from another question. That question is about int vs float const and constexpr, so not exactly a duplicate, but the answer applies here very nicely.

    0 讨论(0)
提交回复
热议问题