简体   繁体   中英

Regarding initialization of bool array in C++

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM