Chapter 8 - FIGURE 8.1

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Chapter 8 - FIGURE 8.1

KaiMonTop
//Returns x*y
function mult (x,y)
push 0
pop sum
push 0
pop i
label WHILE_LOOP
push i
push y
lt
neg
if-goto WHILE_END
...

My question relates to the behaviour of the if statement.
Say that i is 0
Say y is some value above 0
we perform lt(less than)
i < y
this is true
we neg and get -1

if is performed. Since our value is true we then go to the  goto WHILE_END

Is this not terminating our loop early. I fail to understand how this behaviour results in the loop continuing. Please help me understand the logic behind this.
Reply | Threaded
Open this post in threaded view
|

Re: Chapter 8 - FIGURE 8.1

dolomiti7
The NEG doesn't make sense in this context. LT returns either 0 or -1, so the NEG would leave the false case unchanged and the true case would be converted from -1 to +1 which will still be interpreted as true by the if-goto (every value other than 0 is true). Therefore your observation is right, the loop would end early here.

I presume the NEG should be replaced by a NOT, then the code makes sense and will execute as (likely) intended. Generally since LT, GT and EQ leave a boolean constant on the stack, the result has to be inverted with NOT if required.