1

I am surprised that below codes compile and display a right result.

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    char arr[v.size()];  /* why does this line compile? */

    std::cout << sizeof(arr) / sizeof(arr[0]) << std::endl;  /* display 3 */

    return 0;
}

I believe a constant length must be used when defining an array in C/C++. The vector::size() is determined in runtime, so why does this work?

1 Answers1

2

First, C/C++ are two different languages.

C99 defined VLAs (Variable Length Array), but this has been changed to optional in subsequent standards.

C++ doesn't define VLAs.

Thus, this compiles because you are using a compiler that has an extension for, probably GCC. Then strictly speaking, your code is not C++ standard compliant.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69