Reputation: 1366
I understand that programming languages translate certain keywords in computer-readable code, but how can a computer understand it is executing an "if" or a "while" statement when it can only handle ones and zeros? And how did the early programmer's know what to type, using only binary?
Upvotes: 2
Views: 2192
Reputation: 4173
how can a computer understand it is executing an "if" or a "while" statement?
The short answer is that the computer does not understand if or while.
The computer executes one simple instruction after another. Each instruction is located at a particular address. There are special "branch" (or "jump") instructions to jump forwards and backwards in the instruction list. Some of these jump instructions are conditional on the value of certain bits in the CPU. For example there is usually a bit that indicates whether the previous calculation was zero. There are also instructions to set these bits, and special jump instructions that only jump conditionally based on the value of these bits.
Consider this code:
if( a == 0 ){
b = 1;
}else{
b = 2;
}
This might get compiled to machine code something like the following made-up assembly code (and I'm simplifying this to explain how an if statement might be compiled):
;;(address instruction params ;; comments)
10 TEST a ;; set the "ZERO" bit based on whether a is zero
20 JNZ 50 ;; if ZERO bit is *not* set, jump to 50, otherwise fall through to 30
30 STORE b, 1 ;; store 1 in b
40 JUMP 60 ;; jump over else branch
50 STORE b, 2 ;; store 2 in b
60
So the machine knows how to test values and set bits in the status register (that's where the zero bit is stored). And it knows how to conditionally jump forwards and backwards in the instruction stream (you can probably guess how a while loop is implemented: you make a test and jump backwards in the instruction list to make a loop). I guess you could say that the machine has a kind of "if" built in, but it is very simple: it can only jump forwards or backwards.
You might find it informative to study the instruction set of a simple CPU such as the Atmel AVR to get an idea about what a CPU can natively do.
And how did the early programmer's know what to type, using only binary?
I guess they had a big list of all the instructions that the processor knew how to interpret. Or maybe an instruction set manual.
By the way, early programmers didn't type, they entered code on punch cards, or by flipping banks of switches.
Upvotes: 4