0

What is wrong with the pop() function why doesn't it work correctly?

class stack{
    int *p, *Cursor;
    int size ;
public:
    stack(int sz) {Cursor = p = new int[size=sz+1];} //consider the stack empty when its size is 1
    ~stack() {delete[] p;} //Cursor and P will be destroyed when the program finishes
    void push(int x) {Cursor+=1; *Cursor=x; size++;}
    int pop() {if(Cursor == p) return -1; int temp = *Cursor; Cursor--; size--; return (temp);}
    bool isEmpty(){return(Cursor == p);}
    bool isFull(){return(Cursor == p+size);}
};

here is my testing:

stack A(3);
    std::cout<<"Empty: "<<A.isEmpty()<<std::endl;
    std::cout<<"Full: "<<A.isFull()<<std::endl;
    A.push(10);
    A.push(20);
    A.push(30);
    std::cout<<std::endl;
    std::cout<<" 1st pop: "<<A.pop()<<std::endl<<" 2nd pop: " <<A.pop()<<std::endl<<" 3rd pop: " <<A.pop()<<std::endl<<" 4th pop: " <<A.pop()<<std::endl;

the output I get is:

1st pop: -1
2nd pop: 10
3rd pop: 20
4th pop: 30

while I should get sth like:

1st pop: 30
2nd pop: 20
3rd pop: 10
4th pop: -1

The question is where did I go wrong?

A_Matar
  • 2,210
  • 3
  • 31
  • 53

2 Answers2

5

Nothing did go wrong, but the pops get (in your case) evaluated from right to left if you put them all in one std::cout line. In general. the evaluation order is unspecified. For more detail on this see here.

So you correctly get the elements in reverse order of insertion and then -1 and then print them reversed.

Community
  • 1
  • 1
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • Order of evaluation is unspecified, not right-to-left. – Mat Feb 07 '15 at 22:46
  • It's obviously right-to-left in OP's case. – zmbq Feb 07 '15 at 22:47
  • 1
    @Mat Should be right to left because each `<<` is a function call. – Baum mit Augen Feb 07 '15 at 22:47
  • `f(a,f(b))` - you don't know whether `a` or `f(b)` will be evaluated first. It's not left-to-right. – Mat Feb 07 '15 at 22:49
  • http://stackoverflow.com/questions/7718508/order-of-evaluation-of-arguments-using-stdcout http://stackoverflow.com/questions/2129230/cout-order-of-call-to-functions-it-prints http://stackoverflow.com/questions/9377592/please-explain-this-ambiguity – Mat Feb 07 '15 at 22:51
  • @Mat won't `b` (not `f(b)`) be evaluated before `a` ? – Quentin Feb 07 '15 at 23:00
1

In the last line of your code, you make several function calls (hidden, but each << operator is actually a function call). The evaluation of the parameters to these function calls is unspecified. So it is unspecified which "pop() function is called first.

gnasher729
  • 51,477
  • 5
  • 75
  • 98