Search code examples
cinitializationinitializer-listinitializer

Why does this code output the first element in the initializer?


One of my friends sent me this code today:

#include <stdio.h>

int main()
{
    char *s = { "one", "two", "three", "four", "five" };
    puts(s);
}

Its output is:

one

As I know, strings like "one" are translated as addresses in C, which are constants. Thus, "one", "two", "three", "four", "five" is equal to "five" due to comma operators among them. So shouldn't { "one", "two", "three", "four", "five" } be equal to { "five" },creating char *s="five"?


Solution

  • There is no comma operator anywhere in this code. Instead, the commas are seperators in an initializer list.

    The compiler will initialize the char pointer to the first literal in the list and issue a warning like "excess elements in initializer", indicating that the remaining elements in the list have been discarded.

    As was already mentioned in the comments, what your friend intended was probably

    char *s[] = { "one", "two", "three", "four", "five" }
    

    giving s[0]="one", s[1]="two" and so on.