Ordering in an initialization in C, C++

前端 未结 4 1236
日久生厌
日久生厌 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:39

    Is the order of execution f() and g() in any line specified by C and C++ standards?

    In C, No. They can evaluate in any order.

    C11 6.7.9 Initialization

    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).

    While C++11 says that the order of evaluation is deterministic.

    8.5.4:4 List-initialization

    Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (14.5.3), are evaluated in the order in which they appear. That is, every value computation and side effect associated with a given initializer-clause is sequenced before every value computation and side effect associated with any initializer-clause that follows it in the comma-separated list of the initializer-list.


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

提交回复
热议问题