(05-23-2014 05:00 PM)Alvaro Wrote: [ -> ]That with the "Stack" and Variables is one thing that I never could understand, it sounds to me as "joke".
The usage of a Variable on a Program is that it can be used many times. That is the sense of Variables. And NOT only at a Stage of program but ANYTIME you need.
This goes beyond the four-level stack HP put on calculators before they were programmable, so I'll address it outside that context.
Here's an example. I'm finishing up another work project with a low-cost PIC16F microcontroller for a commercial product, with 5,500 lines of code. Its processor has only one register to hold values you're working with, and no direct access to the return stack. Although you can synthesize a data stack in software, the processor's instruction set does not give an efficient way to access bytes other than the one at the top of the stack (or at the bottom in the case of HP calculators' upside-down stacks), limiting its usefulness.
So then, I have a lot of temporary variables-- TEMP_W, TEMP_1, TEMP_2, TEMP_3, TEMP_4, and TEMP_5, LOOP_CNT (loop counter), LOOP_CNT_2, LOOP_CNT_3, and LOOP_CNT_4. These hold values needed temporarily, unlike ones that are long-term. If you were to create a single-purpose variable everywhere you need a
temporary variable, the microcontroller would need more RAM. I've used it all up as it is.
Now I can use temporary variables to pass parameters to and from subroutines, and as loop counters for nested loops; but I have to be extremely careful to make sure that one nested subroutine does not overwrite data that is still needed by another one it's nested with, even six subroutine levels deep. Sometimes it is hard to anticipate which subroutines will get used at the same time, so later debugging may include changing which temporary varialbes a particular routine uses, after doing a search in the source code to find out if such a change will cause other problems.
It goes even further. To get enough variable space in RAM, other variables that are
not general-purpose temporary ones get re-used for something else in the brief times they're not needed for their normal purpose. Again, the programmer must be extremely careful.
Now let's say you have RAM to burn-- ie, more than you could ever need. Doing things this way, you still cannot save environments and have re-entrant routines. Even without that, having such a load of variables may require care choosing unique names, and having so many variables makes it more difficult to keep a project from getting out of control.
These problems could all be avoided if I could use stacks (like Forth's return stack and data stack).