Search code examples
coperator-precedence

Multiple expressions in single statement


I am trying to understand two situations in C.

Situation - 1:

int main() {
    int x = -5, y = 8, z = 2;
    z = y - (y = x);
    printf("%d", z);

    return 0;
}

It prints 0.

Situation - 2:

int main() {
    int x = -5, y = 8, z = 2;
    x = x + y - (y = x);
    printf("%d", x);

    return 0;
}

It prints 8.

Why in situation - 1, after (y = x) value inside y is update to -5 and then used in the outer expression while in situation - 2, even after (y = x) value of outside expression's y is still 8?


Solution

  • Order of evaluation of operands in C is unspecified. As such, expressions like z = y - (y = x) invoke undefined behavior.

    If I compile your first example, gcc actually warns me about this.

    % gcc test.c
    test.c:5:16: warning: unsequenced modification and access to 'y' [-Wunsequenced]
        z = y - (y = x);
            ~      ^
    1 warning generated.
    

    And the output when I run that program is 13.