0

I am a beginner in programming. And I found this stack code on geeks for geeks. I am confused that how the operation like pop() after push() knows that top has been upgraded. For example in this code after three push() operations top is now 2 (that is top=2). Next function pop() is called now. How does this function know that the final state of top is now 2. I am a little confused.

/* C++ program to implement basic stack operations */
#include <bits/stdc++.h>

using namespace std;

#define MAX 1000

class Stack {
  int top = -1;

public:
  int a[MAX]; // Maximum size of Stack

  bool push(int x);
  int pop();
  int peek();
  bool isEmpty();
};

bool Stack::push(int x) {
  if (top >= (MAX - 1)) {
    cout << "Stack Overflow";
    return false;
  } else {
    a[++top] = x;
    cout << x << " pushed into stack\n";
    return true;
  }
}

int Stack::pop() {
  if (top < 0) {
    cout << "Stack Underflow";
    return 0;
  } else {
    int x = a[top--];
    return x;
  }
}

int Stack::peek() {
  if (top < 0) {
    cout << "Stack is Empty";
    return 0;
  } else {
    int x = a[top];
    return x;
  }
}

bool Stack::isEmpty() { return (top < 0); }

// Driver program to test above functions
int main() {
  class Stack s;
  s.push(10);
  s.push(20);

  cout << s.peek();
  cout << s.pop() << " Popped from stack\n";
  cout << s.peek();

  return 0;
}
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • 2
    Your code is C++, please don't tag other unrelated languages. And code on competition sites are *not* good code to learn from, it's often horrible and only display bad habits. If you want to learn C++ please [get some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read or take a couple of classes. That would also help you understand how the code can keep track of variables and their values. – Some programmer dude Oct 22 '20 at 08:34

1 Answers1

0

push operation modifies top class member here:

++top

inside this line

a[++top] = x;  

Also pop operation modifies top in the line

int x = a[top--];

When another operation requires top field, it reads actual value.

MBo
  • 77,366
  • 5
  • 53
  • 86