C: A personal way of understanding STACK

Used this to explain stack to my girlfriend and it worked quite well......

The Stack UnderstandingTo call a function

When calling a function, the stack works as below:

1. Function reached, push arguments(to use) on the stack(inventory), push return address on stack(location of soldier)
2. Jump to function code(take a ride to blacksmith)
3. Increment stack pointer to allow space for local variables (pick up materials needed to sharpen sword)
4. Execute code (sharpen)
5. Pop local variables and arguments off stack (throw away used materials from the inventory)
6. Jump to return address (take a ride back to the soldier and give him the sharpened sword)

So, we can translate this into a more interesting scenario to understand (at least it worked for me):



1. Mission accepted :
           Take the sword from the soldier, sharpen it and take it back to the soldier
2. Put sword into inventories, record where the soldier is at, take a ride to the blacksmith
3. Use a bigger bag to put all the materials needed to sharpen the sword
4. Sharpen the sword
5. Dump all used materials from the inventory




6. Give the sword back to the soldier

Comments

Popular Posts