Creating a array on the stack with the size determined at runtime is allowed by default with g++:
int size;
cout << "Enter array size: "
cin >> size;
MyObject stack_array[size];
According answers of this question, it's a bad idea and I agree. Apparently I should be able to use a g++ flag to enforce strict/standard C++ and get a compiler error. The code still compiles even with the following flags:
g++ -ansi -pedantic -Wall -Wextra -Werror -std=c++0x
How can I prevent this code from compiling?
Here is my version info:
g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/lto-wrapper
Target: i686-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.5.2-8ubuntu4' --with-bugurl=file:///usr/share/doc/gcc-4.5/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.5 --enable-shared --enable-multiarch --with-multiarch-defaults=i386-linux-gnu --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib/i386-linux-gnu --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.5 --libdir=/usr/lib/i386-linux-gnu --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-plugin --enable-gold --enable-ld=default --with-plugin-ld=ld.gold --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu
Thread model: posix
gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)
Upgrade your compiler (it needs to support -Wvla
flag, you can hunt for it in the changelogs or just upgrade to 4.6.2). 4.6 will correctly reject it:
> g++ -std=c++0x -Wall -Werror -pedantic -o vla.exe vla.cpp
vla.cpp: In function 'int main()':
vla.cpp:3:19: error: ISO C++ forbids variable length array 'array' [-Werror=vla]
vla.cpp:3:9: error: unused variable 'array' [-Werror=unused-variable]
cc1plus.exe: all warnings being treated as errors
Also, -ansi
is the same as -std=c++98
, so don't use that flag if you want C++11.
On my computer (Arch Linux, GCC 4.6.2) using g++ -pedantic file.cpp
returns
test.cpp: In function ‘int main()’:
test.cpp:7:12: warning: ISO C++ forbids variable length array ‘arry’ [-Wvla]
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