Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ cout strange behavior with a custom Stack class

Tags:

c++

stack

cout

I have a custom stack class. Most of the code can be seen here:
Member functions of a templated class, that take a template type as argument

I fill the stack like so:

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 this: 1234
However, if I do this:

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

I get this: 4321, which is obviously what I want.

So, what gives?

like image 766
Matt Munson Avatar asked Jun 20 '26 12:06

Matt Munson


2 Answers

The order of evaluation of the function calls is unspecified. Your first expression basically boils down to this:

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

Each of a, b, c, and d are calls to Astack.Pop(). The compiler can generate code that evaluates those calls in any order it chooses.

You should avoid writing expressions that rely on a particular order of evaluation of parts of the expression. In general, it's not safe (and even when it is safe, it is usually quite confusing).

like image 100
James McNellis Avatar answered Jun 23 '26 00:06

James McNellis


In the first version the arguments to cout are evaluated from right to left. You never actually specify which order they should be evaluated in, so the one on the right is evaluated first, popping the 4, and so on.

like image 31
Joel Burget Avatar answered Jun 23 '26 00:06

Joel Burget



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!