Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ variable size array no warning?

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

like image 936
Farzher Avatar asked Jul 27 '13 15:07

Farzher


People also ask

Can I mention array declaration with a variable size?

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.

Why are variable length arrays bad?

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.

Does C++ have VLA?

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.

How do you initialize an array of variable size?

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.


1 Answers

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];
       ^
like image 200
Filip Roséen - refp Avatar answered Sep 23 '22 00:09

Filip Roséen - refp