Reputation: 1430
I have this code below which creates an array of variable size that compiles and runs fine on my mac.
#include <stdio.h>
#include <stdlib.h>
int main(){
int w = 100;
int ar[w];
ar[2] = 42;
printf("%d\n",ar[2]);
}
I thought variable sized arrays were not permitted in C. what is happening here exactly? How is memory being managed? Does the memory get dynamically allocated at run time? Thanks
Upvotes: 0
Views: 327
Reputation: 1090
What's happening here is that variable-length arrays are a relatively new feature, only first appearing in the C standard in 1999. C standards are not adopted as quickly in the C world as JavaScript and Python; I can remember the excitement in 2007 or so when my workflow was finally able to include VLAs.
To add insult to injury, while C++ is a mostly-superset of C, VLAs are not supported, meaning that the common use-case of folks compiling C code with C++ compilers will not work.
There was enough pushback from the compiler vendors that the standard eventually (C11) made VLAs optional, mandating the feature-test macro __STDC_NO_VLA__
instead.
(see ISO stadndard 9899:2011 Programming Languages - C, section 6.7.6.2 4)
Upvotes: 1