Ordering in an initialization in C, C++

前端 未结 4 1239
日久生厌
日久生厌 2021-02-18 22:47

Consider the following initializations:

/* C, C++ */
int a[] = { f(), g() };
struct { int x, y } foo = { f(), g() };

/* C++ */
struct goo { goo(int x, int y);           


        
4条回答
  •  無奈伤痛
    2021-02-18 23:29

    No, in C the order of evaluation of the initializers is unspecified:

    (C11, 6.7.9p23) "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.152)"

    152) In particular, the evaluation order need not be the same as the order of subobject initialization.

    In C++ the behavior is different, and the initializers are evaluated in the order in which they appear (C++11, 8.5.4p4).

提交回复
热议问题