Neither of your examples is legal since n
is not compile time constant and standard C++ doesn't allow non-const length for array initialisation (C does however).
The reason why your second example compiles is, that you address the seemingly only problem your compiler has with your first example, i.e. it is not initialized.
I recommend compiling with all compiler warnings enabled, which probably should be default anyway. You can enable them in GCC for example with -Wall -Wextra
and optionally -Werror
. If you want your compiler to strictly stick to the standard, add -pedantic
, too.
You might want to use std::vector and resize instead. If that is the case, your code would become
#include <vector>
void aa(int n) {
// 1st parameter: number of elements, 2nd: value of elements.
std::vector<int> test(n, 0);
// test.resize(n, 0); // is also possible
// std::fill(test.begin(), test.end(), 0); // is also possible
}
int main() {
aa(10);
return 0;
}