Why should a programmer understand the CPU?

Posted: (EET/GMT+2)

 

When writing applications with programming languages such as C, C++, Pascal or Delphi, you usually do not have to think much about how the computer's processor works. The compiler converts your program into machine instructions which the processor can understand.

I think however that knowing at least the basics of CPU programming can make you a better programmer. Even if you never write a complete application using assembler, it is useful to understand what happens inside the computer when your program is running.

For example, when you create a variable in your program, the compiler must decide where to store its value. It might use the computer's memory or one of the processor's registers. Registers are small storage locations inside the CPU, and accessing them is usually much faster than accessing normal memory.

Another example is calling a procedure or function. In a high-level language this is very simple:

CalculateTotal();

But at the processor level, several things may happen. The program must remember where to return after the procedure has finished, and it may also need to pass parameters and save some register values.

The Intel processors like 486 and Pentium used in most PCs have their own instruction set. Instructions such as MOV, ADD, SUB and JMP are used to move data, calculate values and control program execution.

MOV EAX, 10
ADD EAX, 5

These two assembler instructions place the value 10 into the EAX register and then add five to it. The result is 15.

Understanding simple instructions like these can also help you understand why some programming operations are faster than others, and why certain programming errors can cause unexpected results.

You don't need to stop using Delphi or C++ and start writing everything in assembler. Modern compilers can produce very good machine code, and writing large applications directly in assembler would be quite difficult.

But learning how the CPU works gives you a better understanding of your own programs. It is also quite interesting to see what happens behind the source code.

If you are interested in learning more, Intel provides programmer's manuals which describe the processor registers, instruction set and memory handling in detail.

Hope this helps!