且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C中的数组初始化

更新时间:2022-10-25 22:52:51

这是无效C.见C11 6.7.9:


  

没有初始化将试图以提供一个对象的值不
  其中所包含的实体被初始化


块引用>

我猜你正在使用gcc。然后,如果你希望你的程序表现为严格的标准C,编译这样:

 的gcc -std = C11 -pedantic-错误


  

错误:标量初始化多余的元素


块引用>

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?

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