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:
- the first line sets
x = x + y
(which isx = 20+35 = 55
) (note:x
was incremented, but assigned over top of, so doesn't matter) y
was incremented and is therefore36
- next line increments both, adds the result and sets it as
y
(which isy = 37 + 56 = 93
) - which would be
56
and93
, so the output is5693
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