softwarelover
softwarelover

Reputation: 1019

Why does C++ allow passing the array size at run-time to a function in order to construct a fixed-size array?

According to my opinion, the following piece of code should not compile. Yet, it does and prints perfectly:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

In fact, it does even if I remove "const" from the parameter.

void arrayTest(const int size) {

    int myArray[size];
    for(int i=0; i<size; i++) {
        myArray[i] = i;
    }
    for(int i=0; i<size; i++) {
       cout << myArray[i] << " ";
    }
    cout << endl;

}


int main() {
   arrayTest(15);
   return 0;
}

I am puzzled because I know that the size of an array is a constexp which must be evaluated at compile time. Also, I do not involve any sort of dynamic allocation (i.e. I do not use malloc(), new, etc). The function's local variables are all created on the stack. No heap involvement, whatsoever!

So, why is it compiling?

Upvotes: 4

Views: 328

Answers (1)

eerorika
eerorika

Reputation: 238311

Why does C++ allow passing the array size at run-time to a function in order to construct a fixed-size array?

C++ language does not allow you to use a function parameter as the length of an array variable. The length of an array must be a compile time constant expression.

The length of myArray in your example is not a compile time constant expression, therefore the program is ill-formed.

So, why is it compiling?

Because your compiler chose to do so. The C++ language merely allows the compiler to fail compilation of ill-formed programs. They are allowed to compile succesfully, which lets the compiler to extend the language. You are using a language extension.

The C++ standard does require the compiler to diagnose ill-formed programs (except when allowed not to do so by a specific rule), and if it did not issue a diagnostic message for you, then the compiler does not conform to the standard.

Here is example output from a conforming compiler:

warning: ISO C++ forbids variable length array 'myArray' [-Wvla]

Upvotes: 5

Related Questions