Reputation: 37
So I need to check if the stack is empty before returning a value that is being calculated. if its not empty, then I will raise an error.
How can I check if the stack is empty or not? Compare $sp with null, how? or if starting address of $sp is always the same, should I hard code it? (if address of $sp equal to 270346..3, then empty) (this feels very wrong)
Any help would be appreciated Thanks
Upvotes: 0
Views: 489
Reputation: 26656
You should never check if the call stack is "empty" — this concept doesn't really make sense — the call stack is supposed to always be there.
However, if you are pushing a dynamic number of things onto the stack, and later popping them all of them off, you can either:
Capture the value of stack pointer before any of the dynamic pushing, and then as part of dynamic popping compare the current stack pointer with that previously captured stack pointer — when they are equal, there's nothing to pop.
Alternately, start a count at zero before any dynamic pushing, and add to that count as items are pushed, decrement the count as they are popped — whenever the count is zero, then there's nothing to pop.
On the other hand, if you are writing a program that takes control directly from the simulator or from the operating system, these are special in that there is no one to return to. Because of this, usually we use custom startup code for that, and such startup code is not a classic function.
Any code that is written as a function can assume that it was called, and thus can return to its caller.
Upvotes: 1