Interdependent initialization with commas?

后端 未结 2 1282
谎友^
谎友^ 2021-01-02 03:44

Is the following perfectly defined:

int x = 42, y = x;

i.e. strictly equivalent to:

int x = 42;
int y = x;
<
2条回答
  •  -上瘾入骨i
    2021-01-02 04:06

    The correct answer is that

    int x = 42, y = x;
    

    and

    int x = 42;
    int y = x;
    

    are usually equivalent (not strictly).


    Considering the standard § 8 Declarators [dcl.decl]:

    3 Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.

    and in the footnote [100] further explains:

    A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator. That is

    T D1, D2, ... Dn;

    is usually equivalent to

    T D1; T D2; ... T Dn;

    where T is a decl-specifier-seq and each Di is an init-declarator.

    • The above guarantees that x = 42 and y = x will be evaluated separately. However, as @Praetorian correctly pointed out in the comments, footnotes are not normative.

    • This means that the order of evaluation is not well defined and an implementer could as well implement the evaluation of the declarations in the reverse order (i.e,. T Dn; ...T D2; T D1;).

    • One might argue that the comma operator is guaranteed left to right evaluation. However, this not the case. According to the K & R [K & R II, 3.6 p.63], that also applies to C++:

    The commas that separate function arguments, variables in declarations, etc., are not comma operators, and do not guarantee left to right evaluation.

提交回复
热议问题