Pop by decrementing then reading
Updated
Pop with topIndex as current top: x = a[topIndex]; topIndex -= 1; return x. You may leave a stale value in the slot; it is not on the stack because topIndex moved.
What to focus on
Read first, then decrement. Decrement-first reads the buried value and drops the real top without returning it.
Worked examples
three
a = [4, 1, 9], topIndex = 2- x ← a[2]=9
- topIndex ← 1
Result: popped 9
to empty
a = [7], topIndex = 0- x ← 7
- topIndex ← -1
Result: []
decrement first bug
a = [4, 1, 9], topIndex = 2 → 1 then read- reads 1
- 9 dropped
Result: wrong pop 1
Try it
Write popAt(a, topIndex). a is the array-backed stack. topIndex is the current top, or -1 when empty. Read a[topIndex], then decrement. Decrement first pops the wrong value. a = [4, 1, 9], topIndex = 2 pops 9. a = [7], topIndex = 0 leaves []. Decrement first on [4, 1, 9] wrongly returns 1.
The stack is non-empty (topIndex >= 0) before the pop. Values are integers.