I'm confused with it because if we already have a pointer then we can easily point to next instruction, we can easily point to get back previous function so then why we need another stack pointer register to get back to previous function or module?
The Stack Pointer (SP) register is used to indicate the location of the last item put onto the stack. When you PUT something ONTO the stack (PUSH onto the stack), the SP is decremented before the item is placed on the stack.
The Stack Pointer register will hold the address of the top location of the stack. And the program counter is a register always it will hold the address of the memory location from where the next instruction for execution will have to be fetched.
In conclusion, the main difference between stack pointer and program counter is that the stack pointer is a register that stores the address of the last program request in a stack while the program counter is a register that stores the address of the next instruction to be executed from the memory.
A program counter is a special purpose register that stores the address of the next instruction that needs to be executed. Since the address bus consists of 16 lines in 8085, 16 bits are required to store any address. Thus, PC is 16-bit.
The program counter tells the CPU where it is. The stack is used to (amongst other things) keep a record of where it has been.
If a function is called, that function needs to know where to return to once it has finished. This could indeed simply be an address passed in, but if that function itself calls other functions, or even calls itself recursively, then it needs to ensure that this address is not lost or overwritten - so it must be stored. The natural way of doing that, is to push the address onto a stack, and the pop it back off again when needed.
Of course it also stores the local state for a function, because that too needs to be pushed and popped as the program descends into or returns from functions.
Not all processors necessarily have a stack, but if you do anything remotely complex on one, you inevitably implement one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With