Increment behavior in cout

#include <iostream>
using namespace std;

main(){

int i = 5;

cout << i++ << i--<< ++i << --i << i << endl;


}

The above program compiled with g ++ gives the result:

45555

While the following program:

int x=20,y=35;

x =y++ + y + x++ + y++;

cout << x<< endl << y;

gives the result as

126

37

Can someone explain the way out.

+3
source share
4 answers
cout << i++ << i--

semantically equivalent

operator<<(operator<<(cout, i++),   i--);
           <------arg1--------->, <-arg2->

$ 1.9 / 15- "When a function is called (regardless of whether the function is inline), the calculation of each value and the side effect associated with any argument or postfix expression denoting the called function are sequenced before each expression is executed or in the body of the called function. [ Note: value calculations and side effects associated with different unexpanded argument expressions. -End note ]

C ++ 0x:

, arg1/arg2 ( ).

:

, undefined.

operator<<(operator<<(cout, i++), i--);
                                      ^ the interesting sequence point is right here

, arg1, arg2 i, , , .

undefined. , ?

"undefined " :) .

undefined , ( ), ( ). undefined; O .

@DarkDust ' : -)'

, , , undefined.

.

, defined , , OP, ( ):)

+12

undefined. :-) ( : = ;).

Edit:

. C, 3.2.

+4

:

If you use g++, using the option -Wsequence-pointreports that:

$ g++ -Wsequence-point a.cpp
a.cpp: In function ‘int main()’:
a.cpp:8: warning: operation on ‘i’ may be undefined
                                          ^^^^^^^^^
+3
source

Undefined so anything can happen

+2
source

Source: https://habr.com/ru/post/1770702/


All Articles