-2

stack is popped in function still still shows in main function.

Isn't the call should be by reference for the stack given.

    void showstack(stack <int> s)  { 
        while (!s.empty()) { 
            cout << '\t' << s.top(); 
            //stack getting popped
            s.pop(); 
        } 
    } 

    int main () { 
        stack <int> s; 
        s.push(10); 
        s.push(30); 
        s.push(5); 
        s.push(1); 
        cout << "The stack is : "; 
        showstack(s); 
        //The stack should be empty here.
        cout << "\ns.size() : " << s.size();//size should not get displayed 
        //top should be empty
        cout << "\ns.top() : " << s.top(); 
        cout << "\ns.pop() : "; 
        s.pop(); 
        showstack(s); 
        return 0; 
    } 
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Mohd Zaid
  • 9
  • 3

2 Answers2

0

The function showstack modifies a copy of the stack s, and not the original stack. To work with the original stack pass it around by reference. void showstack(stack <int>& s), note the &. Please be sure not to call top() on an empty stack after returning to main.

rranjik
  • 690
  • 9
  • 21
0

Isn't the call should be by reference for the stack given.

Yes it should, but you didn't.

       //The stack should be empty here.

No, as you passed stack by value to void showstack(stack <int> s), you manipulated a copy of it. The original instance of s stays unchanged.

If you want to operate that function on the original, change the signature to

void showstack(stack <int>& s)
                       // ^

to pass the stack by reference.

       //size should not get displayed 

Stack size can be always displayed.

       //top should be empty

No, as for the same reasons as mentioned above.

Also note there's no empty representation for top(). Accessing it for an empty std::stack is simply undefined behavior.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • so basically they are different form the arrays.. which are generally passed by reference. – Mohd Zaid Mar 30 '19 at 17:30
  • @MohdZaid I don't see how _arrays_ are related here at all. _"which are generally passed by reference."_ They aren't- Raw arrays [decay to pointers](https://stackoverflow.com/questions/1461432/what-is-array-decaying), that's it. – πάντα ῥεῖ Mar 30 '19 at 17:36