Increase problem

Possible duplicate:
Can someone explain these undefined behaviors (i = i ++ + ++ i, i = i ++, etc.)

I have a variable declared as follows:

int j=0;

When I write:

cout<<j++<<" "<<j++<<" "<<j++<<"\n";

I get this output:

2 1 0

I expect to get this output:

0 1 2 

Could you explain the result?

+3
source share
4 answers

The specification states that if you change the same variable more than once at the same point in the sequence, the result will be "undefined".

The points of the sequence are between them; (and also, is a point in the sequence, not sure if there are others).

, , , , " x ?"

int x;
x = 0;
x = x++;

"undefined".

+10

... operator<<( operator<<( operator<<( operator<<(cout,j++), " " ), j++ ), "\n" ); ...

, . , , j ++. j , Undefined Behavior.

[Edit1] . < (int) - _. < < (int) f, < (ostream &, const char *) g.

...g(f(j++)," ").f(j++)...

- : eval (j ++) → eval (j ++) → → call (f) → → call (g) → → (f). - [expr.4]:

, , ,

+6

, , , .

.

Edit: g++ 4.4.0

#include <iostream>

int main (int argc, char **argv) {
int j = 0;
std::cout << j++ << " " << j++ << " " << j++;
return 0;
}
[john@awesome]g++ rtl.cpp -o rtl
[john@awesome]./rtl
0 1 2
[ john @ awesome ]
+3
source

this is confusing, but normal, because the evaluation order for this operator is from right to left.

-1
source

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


All Articles