Search code examples
cstringnull-terminatednull-character

Why is "%s" format specifier working even for a character array without `\0` & printing all its elements at once?


Look at the following code:

#include<stdio.h>

int main(void)
{
    char name[7]={'E','R','I','C'};
    printf("%s",name);
}

It outputs the entire name ERIC.Why is it so?Isn't %s supposed to work only if we initialize the character array name as follows:

    char name[7]={'E','R','I','C','\0'};   //With NULL terminator

I am not considering the following as this obviously assumes a null-terminated character array:

   char name[7]="ERIC"

Solution

  • According to the c11 specification

    (6.7.9.21) If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

    (6.7.9.10) If an object that has static or thread storage duration is not initialized explicitly, then:

    — if it has arithmetic type, it is initialized to (positive or unsigned) zero;

    Thus, when you init an array like this:

    char name[7]={'E','R','I','C'};
    

    It is as same as:

    char name[7]={'E','R','I','C', 0, 0, 0};
    

    So name is still null-terminated.