The short answer
A processor runs instructions in the order they are stored in memory, unless an instruction tells it to go somewhere else. It does this in a repeating cycle: fetch an instruction, decode it, and execute it.
The fetch, decode, execute cycle
- Fetch: the processor reads the instruction at the memory address held in the program counter.
- Decode: the control unit works out what the instruction asks for, such as which registers to use and which operation to perform.
- Execute: the operation is carried out, and any result is stored in a register or in memory.
Some textbook versions add a memory access or write-back step. The names of the stages vary, but the idea is the same.
The program counter
The program counter is a register that holds the address of the next instruction. After the processor fetches an instruction, it usually moves the program counter to the following address. That is what makes sequential execution happen: the next instruction in memory runs next.
When the order changes
Branch and jump instructions change the program counter to a new address, so execution continues somewhere else. High-level selection and iteration often compile down to branch instructions. Function calls and returns also move the flow to a different place and back again.
Interrupts are another exception. An interrupt is a signal from hardware or the operating system that pauses normal execution so the processor can handle an event. The processor then resumes the interrupted work.
Modern processors
Modern processors overlap the stages of several instructions, a technique called pipelining. Some may also run instructions out of order internally. They are designed so the results match what the instructions would produce if they ran in program order. The simple model of one instruction after another still describes what a program appears to do.
From code to instructions
A single line of high-level code, such as an assignment, may become several machine instructions. A compiler may rearrange instructions for speed, as long as the program’s results stay the same. So the order of lines in source code is a guide to the order of work, not an exact record of every machine step.
Scheduling is a separate question
The order in which an operating system switches between running programs is a different question. That topic is covered by cpu scheduling algorithms, and it concerns which program runs next, not the order of instructions inside one program.
Summary
- A processor runs instructions in stored order, using a fetch, decode, and execute cycle.
- The program counter holds the address of the next instruction and normally moves forward.
- Branches, jumps, function calls, and interrupts change the order.
- Internal reordering in modern processors keeps results the same as program order.