0

I have seen code valid in GCC and Clang like:

size_t size;
cin >> size;
int arr[size];

working. But of course this is not supposing to be possible because is not a constant expression. So, why is this? Does the compiler take dynamic memory and frees it automatically for us if we do it like this? (And by the way, this is not valid in Visual C++)

1 Answers1

2

This is what is known as a Variable-length array. It is not a part of C++, but it is supported as an extension by some compilers like GCC and Clang. That's why it compiles fine on those compilers, but it is not legal C++. On GCC you can disable VLAs with this compiler flag:

-Werror=vla

According to GCC documentation:

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits. For example:

FILE *
concat_fopen (char *s1, char *s2, char *mode)
{
  char str[strlen (s1) + strlen (s2) + 1];
  strcpy (str, s1);
  strcat (str, s2);
  return fopen (str, mode);
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93