Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need a stackpointer register when we already have program counter register?

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?

like image 592
shashi kant Avatar asked Dec 24 '12 13:12

shashi kant


People also ask

What is the purpose of a stack pointer register?

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.

What is the role of stack pointer & program counter registers?

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.

Which is more important stack pointer and program counter?

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.

Why stack pointer and program counter are 16bits registered?

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.


1 Answers

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.

like image 86
JasonD Avatar answered Nov 30 '22 06:11

JasonD