Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a constant variable as the size of an array

How come the following code snippet is compiled with no error:

void func(){
    const int s_max{ 10 };
    int m_array[s_max]{0}; 
}

int main() {
    const int s_max{ 10 };
    int m_array[s_max]{0}; 
    return 0;
}

but when I try to define the same array within a class scope, I get the following error:

class MyClass
{
    const int s_max{ 10 }; 
    int m_array[s_max]{0}; // error: invalid use of non-static data member 's_max'
};

Why does s_max need to be static within the class?

I could not find a convincing answer to my question in other similar posts.

like image 771
Monaj Avatar asked Dec 13 '25 14:12

Monaj


1 Answers

As a non-static data member, it might be initialized with different values via different initialization ways (constructors (member initializer lists), default member initializer, aggregate initialization, etc). Then its value won't be determined until the initialization. But the size of raw array must be fixed and known at compile-time. e.g.

class MyClass
{
    const int s_max{ 10 }; 
    int m_array[s_max]{0}; // error: invalid use of non-static data member 's_max'
    MyClass(...some arguments...) : s_max {20} {}
    MyClass(...some other arguments...) : s_max {30} {}
};
like image 98
songyuanyao Avatar answered Dec 15 '25 09:12

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!