Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li><p>You're thinking of the stack backwards - the top of the stack is in the highest valid index, not in <code>val[0]</code>. This behaviour is evident when you look at the pushes of the operands. Your output:</p> <pre><code>3 4 + pass #0 val[0]: 3.00 pass #1 val[0]: 3.00 val[1]: 4.00 </code></pre> <p>First, the <code>3</code> is pushed - going onto the top of the (previously empty) stack - it's in slot 0. Next <code>4</code> is pushed. As you can see, it goes into <code>val[1]</code>, clearly showing that <code>val[0]</code> is not the top of the stack in this case.</p></li> <li><p>You're printing the stack incorrectly, which is confusing you further. Change your print loop to:</p> <pre><code>while (i &lt; sp) { printf("val[%d]: %.2f\n",i,val[i]); ++i; } </code></pre> <p>That is, print only the valid entries in the stack, and you'll see your error.</p> <p>Your current comparison is looking for a <code>0</code> entry on the stack, which isn't how the program is identifying the free entries. That's what the <code>sp</code> variable is used for. In addition to looking for the wrong thing, it's doing it in a bizarro way - <code>val</code> is a an array of floating-point numbers - why are you comparing to a character literal <code>\0</code>?</p> <p>Here's the complete corrected output:</p> <pre><code>3 4 + pass #0 val[0]: 3.00 pass #1 val[0]: 3.00 val[1]: 4.00 pass #2 val[0]: 7.00 7 </code></pre> <p>Now, you see the correct output - both the <code>3.00</code> and <code>4.00</code> are popped, and <code>7.00</code> is pushed back onto the stack. It's now the only valid entry.</p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload