15,878,602 members
See more:
Hello !
Let's suppose that we have a stack based processor , 0-address machine.
We want to calculate A/B or A-B.

So which is the order that arguments should be pushed on stack ?

What I have tried:

1.
PUSH B
PUSH A
DIV

PUSH A
PUSH B
DIV

2.
PUSH B
PUSH A
SUB

PUSH A
PUSH B
SUB
Posted
Dave Kreskowiak 6-Jan-24 19:34pm
Got any documentation on this theoretical processor you're "using"? What each instruction expects is going to be covered and will cover the information like what you're asking.
desanti 6-Jan-24 20:48pm
I have no documentation. I have an comlicated expression to calculate on a stack based cpu with 0 address instruction, but the only problem that i have is the order of arguments for DIV and SUB. But i think if Stack work as LIFO , to get A/B we should do PUSH B , PUSH A , DIV . Because in this order A is on the top of stack and is used as first value.???? But i'm not sure if this is true.
Dave Kreskowiak 7-Jan-24 1:13am
First, you replied to yourself, not me. That means I never got a notice that said you replied.

Next, this is an exercise to set you up for solving the more complex math problems. The idea is for you to think about what would make more sense for the order of operands pushed onto the stack. You've got 2 options. Either A or B gets pushed, then the other operand gets pushed. What would make more sense and where does the answer end up?

You might want to find some resources on virtual stack machines and do a little reading.

## Solution 1

We can't tell you: there is no generic law that states that an imaginary stack-based machine must use operands in any specific order: either order is possible, and it will depend on the way the stack machine was defined: though generally speaking the dividend would be pushed onto the stack first and then the divisor because most expressions are evaluated left-to-right: `X op Y` would evaluate `X` first, so it would be pushed first, then `Y` would be evaluated second and be at the top of the stack as a result.

But it is at the whim of the state machine designer.

desanti 7-Jan-24 13:35pm
so if i understand , the code would be PUSH B , PUSH A , DIV ?
OriginalGriff 7-Jan-24 14:29pm
Probably not - read what I said again.

## Solution 2

desanti 7-Jan-24 13:25pm
Yes , i've already read that article. But the sample that he's using is about + and * where the order of operand is not important. I've not found any aticle that has a sample with / and -.
Richard MacCutchan 8-Jan-24 3:34am
Since these are theoretical machines, it is up to you to decide the order. The article is just about the basic priciples of how such a machine deals with different operations.