Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program Counter?

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

like image 796
Ockham Avatar asked Apr 11 '12 12:04

Ockham


People also ask

Where is the program counter?

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.

What is the content of program counter?

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.


2 Answers

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.

like image 123
sharptooth Avatar answered Nov 09 '22 12:11

sharptooth


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".

like image 43
Sergey Kalinichenko Avatar answered Nov 09 '22 14:11

Sergey Kalinichenko