The program counter (PC) is a register that is part of the central processing unit (CPU). It contains the memory address for the next instruction that has to be executed during the instruction cycle of the microprocessor.
Principle of Operation
Each instruction cycle begins by accessing the instruction stored at the address that is pointed by the program counter and passing it to the instruction register. After that the program counter is updated to point to the address of the next instruction.
The program counter is incremented with a number equal to the size (in bytes) of the last instruction.
The flexibility given by high level languages for creating repeated actions using while structure and control path (decision making) using an if-else structure is made possible by the use of branch and jump instructions where the program counter plays a major role.
A branch instruction performs a comparison and depending on the outcome of the comparison modifies the program counter value:
- if comparison is successful (true) the program counter is modified to take the branch
- if comparison is not successful (false) the program counter is incremented to the next instruction after the branch instruction
The branch instructions modifies the programs counter by adding an offset to its current value. So the new value is always relative to the previous one.
PC = PC + offset
The jump instruction puts a new address into the program counter (unlike the branch instruction that adds an offset) when it is executed during the instruction cycle. When the next instruction cycle begins, a new instruction is fetched from the address that was put by the jump instruction in the previous cycle.