New: HP‑35 SOS

A Stack Overflow Sensing RPN calculator

<<<  Click on the calculator and use your keyboard or mouse, it’s live

To illustrate my idea of stack overflow sensing I modified Neil Fraser’s great JavaScript HP‑35 simulator a little bit: my HP‑35 SOS features a small red LED labeled NO next to the power switch.

NO stands for ‘No Overflow’. This LED lights up as long as there is no stack overflow. When a number is pushed out of the top T‑register your answer might be wrong due to stack overflow, and this is indicated by an extinguished No Overflow LED.

When the NO LED is off, the calculator functions normally. Before starting a longer calculation press the CLR‑key: as long as the red LED remains on you can be sure that your answer is not flawed by stack overflow.

NO: No Overflow !


What is stack overflow?

Look at the following simple calculation:  3 × (4 – (5 × (6 + 7)))
(first work the calculation in your head or on paper to figure out the most natural way to do it)
Doing this calculation in a naive left-to-right way using a classic 4‑level stack RPN calculator will result in the wrong answer because the moment ENTER↑ is pressed for the fourth time (without a two-number operation in-between) the first number on the stack (3) will be lost from the T-register (for details see Appendix A of my RPN Tutorial). Before starting the calculation, for convenience first open the HP‑35 SOS in a separate window and don’t forget to press the CLR‑key even if the red LED is already on!

 3  ENTER↑  4  ENTER↑  5  ENTER↑  6  ENTER↑  7  + ×  ×  Answer: -244   Wrong!

Classic 4‑level stack RPN calculators will give no warning that the answer above is flawed, but in my opinion they should. My HP‑35 SOS shows one way in which this could be achieved: before starting a calculation like the one above in which you would like to be warned of stack overflow, it is important to first press the CLR‑key (not the CLx‑key!): The stack will be cleared and the red LED labelled NO lights up; as long as there is no stack overflow the red LED will remain on; as soon as the stack overflows the red LED will go out to warn you that your answer will not be correct. Try it on the above calculation, and you’ll see that the red LED goes out as soon as you press ENTER↑ for the fourth time!

And then try the following correct ways to do the calculation; you’ll see that the red LED will stay on (press the CLR‑key before starting each new calculation):

 4  ENTER↑  5  ENTER↑  6  ENTER↑  7  + ×   3  ×  Answer: -183 

 5  ENTER↑  6  ENTER↑  7   + ×  4  xswap symboly   3  ×  Answer: -183 

The next line shows the preferred way: start from within the innermost pair of parentheses:
 6  ENTER↑  7   +  5  ×  4  xswap symboly   3  ×  Answer: -183 


How to prevent stack overflow?

Just remember two simple rules of thumb to keep the chances for the occurrence of stack overflow as slim as possible:


By Hans Klaver Last modified: 14 August 2023