Confusion about array initialization in C

后端 未结 7 1320
不知归路
不知归路 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:37

    I don't understand, why does a[0] print 1 instead of 0?

    Presumably a[2]=1 initializes a[2] first, and the result of the expression is used to initialize a[0].

    From N2176 (C17 draft):

    6.7.9 Initialization

    1. The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified. 154)

    So it would seem that output 1 0 0 0 0 would also have been possible.

    Conclusion: Don't write initializers that modifies the initialized variable on the fly.

提交回复
热议问题