> these kinds of things are not allowed?
Correct.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
$ cat foo.cpp
#include <iostream>
int main ( ) {
int n = 10;
int a[n];
a[0] = 0;
std::cout << a[0];
}
$ g++ -Wall -pedantic foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:4:12: warning: ISO C++ forbids variable length array ‘a’ [-Wvla]
int a[n];
^
|
Your current compiler might let you get away without a warning, but later on you might find one that is less generous. But by then, you might be faced with the problem of unlearning a bad coding habit.
> vector is also variable size so is it bad too?
1 2 3 4 5 6 7 8 9 10
|
$ cat foo.cpp
#include <iostream>
#include <vector>
int main ( ) {
int n = 10;
std::vector<int> a(n);
a[0] = 0;
std::cout << a[0];
}
$ g++ -Wall -pedantic foo.cpp
|
No, because vectors are designed to expand.
The danger of VLA's is that you have zero warning and zero change of error recovery should the user type in say a very large (or negative) size for your array. With a VLA, the program will just crash or the OS will kill it.
At least with vector, you always get a
std::bad_alloc exception you can catch, and do something with.
> my college professor also taught us to do like this.
So now you know not to take everything at face value.