Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 45 of 9361. Foundations of Digital Logic and Computer ArchitectureFree lesson

Analyzing PC-Relative Addressing for Control Flow

You will determine how program counter relative addressing enables position-independent code and efficient branching within executable programs.

In this lesson, you will learn how PC-relative addressing allows programs to jump to different locations without needing to know their absolute memory addresses, enabling code to run from any location in RAM.

The Problem with Absolute Addresses

Imagine you write a program that needs to jump to a specific function located at memory address 0x4000. If you "hard-code" this address into your instructions, your program becomes rigid. If you move your program to start at 0x8000 instead of 0x0000, your jump instruction will still point to 0x4000, likely causing the processor to crash because the target code moved with the program.

The PC-Relative Solution

PC-relative addressing solves this by expressing the jump target as an offset from the current Program Counter (PC). Instead of saying, "Jump to address 500," the instruction says, "Jump 10 lines forward from where I am right now."

Because the offset describes the distance rather than the destination, the relationship between the current instruction and the target code remains constant, regardless of where the program sits in memory. This is the foundation of Position-Independent Code (PIC).

A Concrete Example

Consider a simple branch:

PC: 0x100  CMP R1, R2      ; Compare two values
PC: 0x104  BEQ 0x08        ; Branch if equal to (PC + 4 + 8)
PC: 0x108  ...             ; Skipping instructions
PC: 0x110  TARGET_LABEL    ; Destination

In the example above, the instruction BEQ uses an offset of 8. When the processor executes this, it takes its current address (0x104), adds the size of the instruction (4 bytes), and adds the offset (8), landing perfectly at 0x110. If you shifted the entire block of code to start at 0x500, the math would still work perfectly: 0x504 + 4 + 8 = 0x510.

This mechanism makes branching efficient because offsets are often smaller than full memory addresses, allowing us to squeeze jump instructions into smaller, fixed-width formats while keeping our software flexible.

Key Takeaway: PC-relative addressing uses an offset relative to the Program Counter, making programs relocatable and independent of their absolute location in memory.