Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Compiler error or just unexpected result due to allowed optimization ???

28 views
Skip to first unread message

Bob Langelaan

unread,
Oct 9, 2015, 11:45:15 PM10/9/15
to
If I have the following code:

int var2 = 12;
int var3 = 20;

cout << '\n' << var2++ << " " << ++var2;
cout << '\n' << var2;

cout << "\n\n" << --var3 << " " << var3--;
cout << '\n' << var3;

I expect the output:

12 14
14

19 19
18

But with Microsoft Visual Studio 2013 I get instead:

13 14
14

18 20
18

I apologize if this question has been posted before.

Thanks,
Bob

Paavo Helde

unread,
Oct 10, 2015, 3:56:35 AM10/10/15
to
Bob Langelaan <bobl...@gmail.com> wrote in news:e97438d7-404f-4a80-bc21-
cc697a...@googlegroups.com:

> If I have the following code:
>
> int var2 = 12;
> int var3 = 20;
>
> cout << '\n' << var2++ << " " << ++var2;
> cout << '\n' << var2;
>
> cout << "\n\n" << --var3 << " " << var3--;
> cout << '\n' << var3;

The behavior is undefined, anything can happen.

If instead of an int a class with user-defined ++ and -- operators was
used, then the behavior would be just unspecified and there would be a
couple of possible outputs, depending on which arguments happen to be
evaluated first.

IOW: don't write such code.
0 new messages