is this form of intializing an array to all 0s
char myarray[ARRAY_SIZE] = {0} supported by all compilers? ,
if so, is there similar syntax to other types? for example
bool myBoolArray[ARRAY_SIZE] = {false}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language
= { 0 }is an idiomatic universal zero-initializer. This is also almost the case in C++.Since this initalizer is universal, for
boolarray you don’t really need a different “syntax”.0works as an initializer forbooltype as well, sois guaranteed to initialize the entire array with
false. As well asin guaranteed to initialize the whole array with null-pointers of type
char *.If you believe it improves readability, you can certainly use
but the point is that
= { 0 }variant gives you exactly the same result.However, in C++
= { 0 }might not work for all types, like enum types, for example, which cannot be initialized with integral0. But C++ supports the shorter formi.e. just an empty pair of
{}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.