C – Array Initialization Techniques

arraysc++

I have doubt regarding the following piece of code :

int main()
{
    int array1 = {1,2,3,4,5}; //error in c++ , warning in c
    int array2[] = {1,2,3,4,5};
    int array3[5] = {1,2,3,4,5};
}

This piece of code gives a error on line 3 in c++ but not in c?

I know array1 is actually an int and array2 and array3 are arrays, so why doesn't a c compiler show a error , but just a warning: "excess elements in scalar initialization"

Is there a use of such a definition and why is it valid in c?

Best Answer

It is not valid C. See C11 6.7.9:

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

I would guess that you are using gcc. Then if you want your program to behave as strict standard C, compile it as such:

gcc -std=c11 -pedantic-errors

gives

error: excess elements in scalar initializer

Related Question