Reputation: 143
I was doing one programming problem, there I initialized the bool array like following:-
bool hash[n] = {0};
I submitted the code and I got the wrong answer. I tried to figure out what is the problem. Then I changed the above statement to following:-
bool hash[n];
fill(hash, hash + n, 0);
This gave correct answer. I didn't understand why the bool array initialization is not working.
After that just out of curiosity, I tried following:-
bool hash[n] = {0};
fill(hash, hash + n, 0);
I submitted the code and I got wrong answer. This really blew my mind. Any inputs?
Upvotes: 1
Views: 238
Reputation:
I was able to reproduce this error by going through a few online c++ compilers. (some of them accept VLAs following C99 and don't throw any errors)
Writing
int n=20;
bool hash[n]={0};
throws:
main.cpp:6:13: error: variable-sized object may not be initialized bool hash[n]={0}; ^ 1 error generated. compiler exit status 1
As extensively discussed in the comments above, declaring array size/length at runtime is not a feature of standard C++.
However, this would work:
int n=20;
bool hash[n];
because the array elements are not specified/initialized.
For reproducability, here is the link of the online compiler which produced this case.
Always use vectors for such cases.
Upvotes: 2