assemblycpu-architectureprogram-counter

What does the Program counter have as next instruction when a program ends?


What's the state of the program counter once the last instruction is being executed in a program as there's no next instruction to be fetched?


Solution

  • The program counter register (PC) otherwise known as the instruction pointer (IP) always points at the next instruction to be executed. When an instruction is fetched, the PC is set to point to the next instruction, and it keeps pointing at the next instruction while the instruction that was previously fetched is being executed.

    There is no such thing as "no more next instructions to be fetched".

    Just because your program has no more instructions to execute, it does not mean that the CPU has nothing else to do. Depending on the operating system, your program may end with a RET instruction which returns to the operating system, or it may end with some other instruction that in some other way returns control back to the operating system. Rest assured that the fact that your little program has ended is of very little importance to the operating system; the operating system always has more stuff to do.

    If the operating system decides to put the CPU in some low-power state, there are various ways in which this may be achieved, but the general concept is that the CPU clock is frozen for a certain period of time. When the CPU clock resumes, execution continues exactly there where the PC left off, as if the clock was never frozen.