Search code examples
c++arraysnullinitializationzero

Is initializing every variable in an array to '0' the same as initializing all of them to null?


I have been learning about using null-terminators in C++ arrays and I have been wondering if initializing an array to 0 is the same as initializing it to null.

For example:

char setOfCharacters [15] = {'\0'};

compared to

char setOfCharacters [15] = {0};

I know that initializing setOfCharacters to 0 means that every memory location in the array holds a 0 to start out with. Does initializing it to a null accomplish the same thing?


Solution

  • In fact this initialization

    char setOfCharacters [15] = {0};
    

    is equivalent to

    char setOfCharacters [15] = { (char )0};
    

    setting 0 to an object of the type char can be also written using character literal '\0'.

    And the result of both initializations

    char setOfCharacters [15] = {'\0'};
    

    and

    char setOfCharacters [15] = {0};
    

    is that all other elements of the array that were not explicitly initialized will be zero initialized.

    Take into account that the comparison

    '\0' == 0
    

    always yields true. The character literal in this comparison is promoted to the type int (in C character constants even have the type int, so '\0' is 100% equivalent to 0 there).