Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"const variables" set by a constructor for expressing the bounds of a C++ array?

The following code compiles and it seems to run fine:

class Test {
  private:
     const unsigned MAX;

  public:

     Test (const unsigned int n) : MAX(n) { }

     void foo () {
         int array[MAX];
         ...
     }

};

but is it really OK? I mean:

Test a (3);
Test b (8);

does array actually have 3 and 8 cells respectively?

If so, is it because array is an automatic var and gets instantiated with the appropriate dimension?

Thanks

like image 880
cibercitizen1 Avatar asked Jan 17 '23 05:01

cibercitizen1


2 Answers

What you have written is valid in c99 but not valid c++.

I am of course talking about your use of VLA's, not the full snippet.


When compiling using g++ -pedantic -ansi -Wall we get the below warning;

foo.cpp: In member function 'void Test::foo()':
foo.cpp:18:23: warning: ISO C++ forbids variable length array 'array' [-Wvla]

As mentioned in the above warning the pattern you are using is often referred to as using a variable length array, which is standard in C99 and "allowed" in C++ through a g++ extension.

I'd recommend you to use a STL container instead of hacks as these, for one single reason; what you are doing is not legal, and therefor isn't guaranteed to be portable cross compilers.

like image 94
Filip Roséen - refp Avatar answered Jan 30 '23 13:01

Filip Roséen - refp


Variable length arrays are not standard C++. You could make Test a template instead:

template <int MAX>
class Test {
public:
    Test () {}

    void foo () {
        int array[MAX];
    }
};

Test<4> t4;
Test<8> t8;
like image 23
hmjd Avatar answered Jan 30 '23 13:01

hmjd