C ++ cout weird behavior with custom stack class

I have my own stack class. Most of the code can be seen here:
Template member functions that take a template type as an argument

I populate the stack like this:

stack <int> Astack;
Astack.Push(1); Astack.Push(2); Astack.Push(3); Astack.Push(4);

Then I do this:

cout << Astack.Pop() << Astack.Pop() << Astack.Pop() << Astack.Pop() <<endl;

and get the following: 1234
However, if I do this:

cout << Astack.Pop(); cout << Astack.Pop(); cout << Astack.Pop(); cout << Astack.Pop();

I get this: 4321, which obviously I want.

So what gives?

+3
source share
3 answers

The procedure for evaluating function calls is not specified. Your first expression basically boils down to the following:

cout << a << b << c << d;

Each of the a, b, cand dis a challenge Astack.Pop(). The compiler can generate code that evaluates these calls in any order that it chooses.

, . , ( , ).

+7

cout . , , , 4 ..

+1

There is something known as Unspecified Behavior defined by the ISO C ++ standard. Your code snippet is just an example of this.

+1
source

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


All Articles