Reputation: 3596
When I learned C using Microsoft Visual Studio, it didn't allow me to create an array with a non-constant size. I had to either put a value like int arr[5];
or do #define size 5
and do int arr[size];
. However today using Clion, I noticed it allows me to do the following:
#include <stdio.h>
int main()
{
printf("Enter a value: ");
int x;
scanf("%d", &x);
int arr2[x];
for (int i = 0; i < x; i++)
{
arr2[i] = i;
printf("Array at %d is %d.\n", i, arr2[i]);
}
return 0;
}
This C code compiles and runs without any problems -- no segment fault or anything. What's going on? Is this legal C code and I just learned in an IDE that didn't allow it, or is this invalid C code and I'm just using a bad compiler? On my other computer which is using Linux, I even installed GCC 7.2 and the same syntax is allowed. I don't understand. Is this a CLion issue, CMake issue, or a C lang issue?
My compiler and CMake are listed below. Thanks.
Upvotes: 1
Views: 260
Reputation: 224387
This is valid C. It is referred to as a variable length array (VLA). This feature was added to the language as part of the C99 standard.
MSVC is well known for not supporting many C99 and later features, including VLAs.
Upvotes: 7