Confusion about array initialization in C

后端 未结 7 1308
不知归路
不知归路 2020-12-12 18:13

In C language, if initialize an array like this:

int a[5] = {1,2};

then all the elements of the array that are not initialized explicitly w

7条回答
  •  再見小時候
    2020-12-12 18:34

    I believe, that int a[5]={ a[2]=1 }; is a good example for a programmer shooting him/herself into his/her own foot.

    I might be tempted to think that what you meant was int a[5]={ [2]=1 }; which would be a C99 designated initializer setting element 2 to 1 and the rest to zero.

    In the rare case that you really really meant int a[5]={ 1 }; a[2]=1;, then that would be a funny way of writing it. Anyhow, this is what your code boils down to, even though some here pointed out that it's not well defined when the write to a[2] is actually executed. The pitfall here is that a[2]=1 is not a designated initializer but a simple assignment which itself has the value 1.

提交回复
热议问题