Search code examples
cc-strings

Are defined strings set to all NULLs?


I could have sworn that I read that a string that was defined but not initialized was set to all NULLs. In other words, that

char string[10];

consisted of 10 null characters, and that

char string[10] = "Kevin";

consists of the letters 'K', 'e', 'v', 'i', 'n' and five nulls.

Is this true:

  1. Always?
  2. Sometimes, depending on the compiler?
  3. Never?

Solution

  • in other words, that char string[10]; consisted of 10 null characters,

    That depends where and on the variable.

    char here_yes[10]; // 10 '\0' characters
    int main() {
        char here_no[10]; // 10 unknown garbage values
        static char but_here_also_yes[10]; // also 10 '\0' characters
    }
    

    and that char string[10] = "Kevin"; consists of the letters 'K', 'e', 'v', 'i', 'n' and five nulls. Is this true: Always?

    Yes. If you partially initialize a string or a variable, the rest is filled with '\0' or zeros.

    char this_has_10_nulls[10] = "";
    int main() {
        char this_has_ab_followed_by_8_nulls[10] = { 'a', 'b' };
        static char this_has_Kevin_followed_by_5_nulls[10] = "Kevin";
    }