mardi 28 juin 2016

Strange post-increment behaviour in C++


I have a friend who is getting different output than I do for the following program:

int main() {
    int x = 20, y = 35;
    x = y++ + x++;
    y = ++y + ++x;

    printf("%d%d", x, y);

    return 0;
}

I am using Ubuntu, and have tried using gcc and clang. I get 5693 from both.

My friend is using Visual Studio 2015, and gets 5794.

The answer I get (5693) makes most sense to me, since:

  1. the first line sets x = x + y (which is x = 20+35 = 55) (note: x was incremented, but assigned over top of, so doesn't matter)
  2. y was incremented and is therefore 36
  3. next line increments both, adds the result and sets it as y (which is y = 37 + 56 = 93)
  4. which would be 56 and 93, so the output is 5693

I could see the VS answer making sense if the post-increment happened after the assignment. Is there some spec that makes one of these answers more right than the other? Is it just ambiguous? Should we fire anyone who writes code like this, making the ambiguity irrelevant?

Note: Initially, we only tried with gcc, however clang gives this warning:

coatedmoose@ubuntu:~/playground$ clang++ strange.cpp 
strange.cpp:8:16: warning: multiple unsequenced modifications to 'x' [-Wunsequenced]
    x = y++ + x++;
      ~        ^
1 warning generated.

Aucun commentaire:

Enregistrer un commentaire