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
  • 1,720
  • 3
  • 23
  • 45

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
  • 46,177
  • 22
  • 136
  • 173
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
  • 47,695
  • 5
  • 65
  • 91