int a;
cin >> a;
int ints[a];
Why does this not throw any kind of warning while compiling? How do I know when this array thing is actually using the heap or the stack?
g++ -std=c++11 -Wall *.cpp -o main
Rather than trying to sort this mess out, the standard forbids it. "size is a variable and C does not allow variable size arrays." we should add a point to your comment that: if we initialize the variable, C does allow defining an array using that variable. E.g. int size = 5; int a[size]; is totally fine.
The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.
VLA is a C99 feature but not extended to C++, because C++ says vectors almost always better then VLA, it's probably too much of work for compiler writers to implement them for the rare cases where they might be better than vectors. nevertheless some compilers like gcc supports them through compiler extensions.
Master C and Embedded C Programming- Learn as you go Variable sized arrays are data structures whose length is determined at runtime rather than compile time. These arrays are useful in simplifying numerical algorithm programming. The C99 is a C programming standard that allows variable sized arrays.
ISO C++ disallows the use of variable length arrays, which g++
happily tells you if you increase the strictness of it by passing it the -pedantic
flag.
Using -pedantic
will issue a warning about things breaking the standard. If you want g++
to issue an error and with this refuse compilation because of such things; use -pedantic-errors
.
g++ -Wall -pedantic -std=c++11 apa.cpp
apa.cpp: In function ‘int main(int, char**)’:
apa.cpp:8:13: warning: ISO C++ forbids variable length array ‘ints’ [-Wvla]
int ints[a];
^
apa.cpp:8:7: warning: unused variable ‘ints’ [-Wunused-variable]
int ints[a];
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With