Search code examples
c++operator-precedence

Sequence-before relation in comma-separated variable definitions


Let's begin with the following example code:

int a = 0, b = a++, c = a;

Is a++ sequenced before a (within c = a)? a++ and a seem to qualify as full expressions, and according to cppreference (Rule 1), the answer should be positive. But I'm not sure.


Solution

  • Yes. As Brian points out, this is not a comma operator, but rather an init-declarator-list. From [dcl.decl] we have:

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

    With a footnote which clarifies:

    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.

    There are two exceptions, one for a name hiding a type and one for auto, neither of which apply. So ultimately, the code you have is exactly equivalent to:

    int a = 0;
    int b = a++;
    int c = a;
    

    Which you should prefer to write in the first place since it doesn't take searching through the standard to ensure that you're doing something valid!