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

RegisterFull NameMain PurposeAutomatically Modified?Memory Direction
PCProgram CounterHolds address of next instruction✅ (each cycle or on jump)Forward (instruction address sequence)
SPStack PointerPoints to top of stack in RAM✅ (during push/pop, calls)Typically downward

 In Context: Function Call Example

c

void foo() { int x = 42; }
  • PC: Fetches address of foo, executes it step-by-step.

  • SP: Stores return address and allocates space for variable x.

评论

此博客中的热门博文

How To Connect Stm32 To PC?

What are the common HDL languages used in FPGA design?

How do you set up ADC (Analog-to-Digital Converter) in STM32?