Im experiencing some pretty strange behavior here. I have a stack class, and I was testing it, but I cant really tell whats wrong with it. Actually, the class seems to be working, but cout is behaving strangely.
Heres the problem. Suppose we push a, b and c. If you pop 3 times, you will get c, b and a. So far so good. This works as expected,
Code:
cout << stack.pop();
and it will print the last value we pushed(c). It works, but this one line doesnt work at all:
Code:
cout << stack.pop() << ' ' << stack.pop();
it will print "b c", in that order. As far as I know, it should print "c b". Strangly enough, this one works ok:
Code:
cout << stack.pop() << ' ';
cout << stack.pop();
It prints "c b".
Then I used this:
Code:
int i;
cout << (i = stack.pop()) << ' ' << stack.pop();
And yes, it prints "c b". It gives the value of c to i, even though without i = stack.pop() it will print "b c".
if you use this
Code:
cout << (i = stack.pop()) << ' ' << stack.pop() << ' ' << stack.pop();
it will print "c a b".
Its a funny behavior, and though its not a big problem I thought about asking what Im doing wrong. Why is cout behaving like this? Am I missing something obvious here?
I don't think my stack class is wrong, but then again... We usually think our code is ok. Im aware of that, but using int i = stack.pop() will get the last pushed value, as it should be. So this works:
Code:
int i = stack.pop();
cout << i;
One thing that should be noticed, it looks like its printing from right to left. It will always print the last pushed value, anteceded by any other value we "pop". So if we push a, b, c and d and then pop three times, we get b, c and d, in that order, not "a, b, c" nor "d, c, b".
Now a piece of the actual code. This prints "3 2 1"
Code:
int main()
{
DStack stack;
stack.push16(0);
stack.push16(1);
stack.push16(2);
stack.push16(3);
for(int i = 0; i < 3; i++)
cout << stack.pop16() << ' ';
cin.get();
return(0);
}
And this, "1 2 3"
Code:
int main()
{
DStack stack;
stack.push16(0);
stack.push16(1);
stack.push16(2);
stack.push16(3);
cout << stack.pop16() << ' ' << stack.pop16() << ' ' << stack.pop16();
cin.get();
return(0);
}
Is this what should be happening? Because "cout << 2 << ' ' << 1;" prints 2 1, not 1 2.
Thanks for taking the time.