What is the role of the Program Counter (PC) and Stack Pointer (SP)?
The Program Counter (PC) and Stack Pointer (SP) are two essential registers in a microprocessor or microcontroller. They serve critical but distinct roles in instruction execution and memory management:
1. Program Counter (PC)
Definition:
The Program Counter holds the memory address of the next instruction to be executed.
Role:
-
Controls the flow of program execution.
-
After each instruction is fetched from memory, the PC is automatically incremented to point to the next instruction.
-
In the case of jumps, branches, or function calls, the PC is modified to point to a new instruction address.
Example Behavior:
If the PC contains 0x08000000
, and a 32-bit instruction is executed, the PC updates to 0x08000004
(next instruction address).
2. Stack Pointer (SP)
Definition:
The Stack Pointer holds the memory address of the top of the stack — a special area of RAM used for temporary data storage.
Role:
-
Manages the stack, which is used to store:
-
Return addresses
-
Local variables
-
Function parameters
-
Register values during interrupts or function calls
-
-
Grows downward or upward in memory, depending on the CPU architecture (STM32, ARM = downward).
-
Modified automatically during function calls (
PUSH
,CALL
) and returns (POP
,RET
).
Example Behavior:
If the SP contains 0x20001000
, and a 4-byte value is pushed, SP becomes 0x20000FFC
.
Summary Table
Register | Full Name | Main Purpose | Automatically Modified? | Memory Direction |
---|---|---|---|---|
PC | Program Counter | Holds address of next instruction | ✅ (each cycle or on jump) | Forward (instruction address sequence) |
SP | Stack Pointer | Points to top of stack in RAM | ✅ (during push/pop, calls) | Typically downward |
In Context: Function Call Example
-
PC: Fetches address of
foo
, executes it step-by-step. -
SP: Stores return address and allocates space for variable
x
.
评论
发表评论