Search code examples
c++standardsc-strings

initialization Standard for char[](c-string)


consider the following piece of code:

int main(){
    char hi[5] = "Hi!";
    printf("%d", hi[4]);    
}

What will be printed? More importantly, Is there a mention in the standard about what will be printed, in the newest C++ standards? If there is a mention, where is it?

For some reason recent information about this is tremendously hard to find, and various sources have conflicting information. I've tried en.cppreference.com and cplusplus.com, the former did not have any info, the latter claimed the values are undetermined. However,

using namespace std;
int main(){
    char mySt[1000000] = "Hi!";
    for(int i=0;i<1000000;++i){
        if(mySt[i]!='\0') cout << i <<endl;
    }
}

This prints only 0, 1, and 2 on my system, and so I expect the "rest" to be initialized to '\0'. Also to my knowledge char mySt[100000]="" initializes the whole array '\0', and it just feels awkward to say that it's different with any other string literal. However my instructor claims otherwise(he claims it is "undefined"), I need to back up my claim with recent and concrete evidence, if there is any.

I compiled on MinGW g++ 8.2.0. Thank you in advance.

To clarify,


Solution

  • In both C++17 and the current C++20 draft, section [dcl.init.string] discusses initializing a character array with a string literal. Paragraph 3 of that section reads:

    If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized.

    So yes, all array elements beyond the ones initialized by characters in the literal are guaranteed to be zero values.