logoalt Hacker News

pavonyesterday at 8:55 PM1 replyview on HN

Nope. Order of evaluation and operator precedence are completely unrelated. They should have been defined to be the same, but instead order of evaluation was left undefined. So if you write ++a + a++, operator precedence means this will be interpreted as (++a) + (a++), not say ++(a + a)++, but it is up to the compiler whether to execute ++a or a++ first, rather than executing them left to right.


Replies

binaryturtleyesterday at 9:25 PM

Sometimes it helps to test. Which I just did. :-)

Actually the compiler (at least clang) warns about this:

    $ gcc -W -Wall test.c -o test
    test.c:8:7: warning: multiple unsequenced modifications to 'a' [-Wunsequenced]
            a = a++ + ++a;
                 ^    ~~
    1 warning generated.
The undefined behaviour stems from the fact that "a" is modified multiple times between the "sequence points" (so it's irrelevant to the actual problem that this happens with ++, --, pre-, or, post-, or in which order) We only can modify the variable safely once on the right side without entering bizarro world.

A construct like this certainly can be confusing.