If I understand this correctly, the program counter points to the address of the instruction to be executed and in most cases you add four to the program counter to advance to the next instruction address. But say you have a program counter that's pointing to a word (e.g word 15) in memory and you want to advance to the next instruction, are you suppose to add 4 directly to 15 in order to get the next instruction?? Any explanation would be appreciated
Program Counter is a register in the CPU hardware. Effectively it's a digital counter so consists of binary latches where each latch represents a binary bit. Number of latches,ie the size of the PC depends on the processor architecture.
A program counter contains the memory location of the next instruction. We can view a program counter as a modern digital counter. It facilitates faster execution of the instructions. Furthermore, it provides tracking of the execution points while the CPU executes the instructions.
That thing is called instruction pointer. Once the processor decodes the current instruction it finds how many bytes it occupies and knows how much to add to the current instruction pointer value to advance to the next instruction so that when the current instruction gets executed the processor knows what to do next.
So for example the processor starts with the instruction pointer storing value 15 as in your example - it looks what happens to be at that address, there happens to be an instruction occupying 5 bytes, no problem - it adds 5 to the current value and this yields 20 and so the instruction pointer now stores value 20 and the processor then executes the current instruction.
You never advance program counter directly - CPU does it for you by executing your program. As the programmer, you manipulate program counter by executing various jump instructions (conditional, unconditional, jumps to subroutine, etc.) One specific case when you need to add an offset to the program counter is when you branch in position-independent code. However, even in this case you do not add the size of the instruction to the program counter: instead, you provide the offset of the place to which you would like to jump by executing a "branch to relative address".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With