MPE/iX Shell and Utilities Reference Manual, Vol 1

dc(1) MPE/iX Shell and Utilities dc(1)
Reverse Polish Notation
To use dc you must understand reverse Polish notation. This is a way to write arithmetic
expressions. The form is a bit tricky for people to understand, since it is geared towards mak-
ing it easy for the computer to perform calculations; however, most people can get used to the
notation with a bit of practice.
Reverse Polish notation stores values in a stack. A stack of values is just like a stack of books:
one value is placed on top of another. When you want to perform a calculation, the calcula-
tion uses the top numbers on the stack.
For example, here’s a typical addition operation:
12+
When dc reads a number or a string, it just puts the value onto the stack. Thus 1 goes on the
stack, then 2 goes on the stack. When you put a value onto the stack, we say that you push it
onto the stack. When dc reads the operator +, it takes the top two values off the stack, adds
them, then pushes the result back onto the stack. After this addition, the stack contains
3
As another example, consider
234+*
(The * stands for multiplication.) dc begins by pushing the three numbers onto the stack.
When it finds the +, it takes the top two numbers off the stack and adds them. (Taking a value
off the stack is called popping the stack.) dc then pushes the result of the addition back onto
the stack in place of the two numbers. Thus the stack contains
27
When dc finds the * operator, it again pops the top two values off the stack. It multiplies
them, then pushes the result back onto the stack, leaving
14
The following list gives a few more examples of reverse Polish expressions. After each, we
show the contents of the stack, in parentheses.
72- (5)
2 7 - (-5)
12 3 / (4)
_12 3 / (-4)
1-156 Commands and Utilities