C Primer Plus 學習筆記_Chapter1 Getting Ready
The life of a CPU, at least in this simplistic account, is quite simple. It fetches an instruction
from memory and executes it. It fetches the next instruction from memory and executes it,
and so on. (A gigahertz CPU can do this about a billion times a second, so the CPU can lead its
boring life at a tremendous pace.) The CPU has its own small workspace, consisting of several
registers , each of which can hold a number. One register holds the memory address of the next
instruction, and the CPU uses this information to fetch the next instruction. After it fetches
an instruction, the CPU stores the instruction in another register and updates the first register
to the address of the next instruction. The CPU has a limited repertoire of instructions (known
as the instruction set ) that it understands. Also, these instructions are rather specific; many of
them ask the computer to move a number from one location to another—for example, from a
memory location to a register.
A couple interesting points go along with this account. First, everything stored in a computer is
stored as a number. Numbers are stored as numbers. Characters, such as the alphabetical characters
you use in a text document, are stored as numbers; each character has a numeric code.
The instructions that a computer loads into its registers are stored as numbers; each instruction
in the instruction set has a numeric code. Second, computer programs ultimately have to be
expressed in this numeric instruction code, or what is called machine language .
One consequence of how computers work is that if you want a computer to do something, you
have to feed a particular list of instructions (a program) telling it exactly what to do and how
to do it. You have to create the program in a language that the computer understands directly
(machine language). This is a detailed, tedious, exacting task. Something as simple as adding
two numbers together would have to be broken down into several steps, perhaps something
like the following:
1. Copy the number in memory location 2000 to register 1.
2. Copy the number in memory location 2004 to register 2.
3. Add the contents of register 2 to the contents of register 1, leaving the answer in
register 1.
4. Copy the contents of register 1 to memory location 2008.
And you would have to represent each of these instructions with a numeric code!
If writing a program in this manner sounds like something you’d like to do, you’ll be sad to
learn that the golden age of machine-language programming is long past. But if you prefer
something a little more enjoyable, open your heart to high-level programming languages.