Chapter 1 Getting Ready

What Computers Do

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.

 

The First ANSI/ISO C Standard


As C evolved and became more widely used on a greater variety of systems, the C community realized it needed a more comprehensive, up-to-date, and rigorous standard. To meet this need, the American National Standards Institute (ANSI) established a committee (X3J11) in 1983 to develop a new standard, which was adopted formally in 1989. This standard (ANSI C) defined both the language and a standard C library. The International Organization for Standardization adopted a C standard (ISO C) in 1990. ISO C and ANSI C are essentially the same standard. The final version of the ANSI/ISO standard is often referred to as C89 (because that’s when ANSI approval came) or C90 (because that’s when ISO approval came). Also, because the ANSI version came out first, people often used the term ANSI C .
The committee had several guiding principles. Perhaps the most interesting was this: Keep the spirit of C. The committee listed the following ideas as expressing part of that spirit:
 

■ Trust the programmer.
■ Don’t prevent the programmer from doing what needs to be done.
■ Keep the language small and simple.
■ Provide only one way to do an operation.
■ Make it fast, even if it is not guaranteed to be portable.


By the last point, the committee meant that an implementation should define a particular operation in terms of what works best for the target computer instead of trying to impose an abstract, uniform definition.

 

Using C: Seven Steps

 

Step 1: Define the Program Objectives


Naturally enough, you should start with a clear idea of what you want the program to do. Think in terms of the information your program needs, the feats of calculation and manipulation the program needs to do, and the information the program should report back to you. At this level of planning, you should be thinking in general terms, not in terms of some specific computer language.

 

 


Step 2: Design the Program


After you have a conceptual picture of what your program ought to do, you should decide how the program will go about it. What should the user interface be like? How should the program be organized? Who will the target user be? How much time do you have to complete the program?
You also need to decide how to represent the data in the program and, possibly, in auxiliary files, as well as which methods to use to process the data. When you first learn programming in C, the choices will be simple, but as you deal with more complex situations, you’ll find that these decisions require more thought. Choosing a good way to represent the information can often make designing the program and processing the data much easier. Again, you should be thinking in general terms, not about specific code, but some of your decisions may be based on general characteristics of the language. For example, a C programmer has more options in data representation than, say, a Pascal programmer.

 

 

Step 3: Write the Code


Now that you have a clear design for your program, you can begin to implement it by writing the code. That is, you translate your program design into the C language. Here is where you really have to put your knowledge of C to work. You can sketch your ideas on paper, but eventually you have to get your code into the computer. The mechanics of this process depend on
your programming environment. We’ll present the details for some common environments soon. In general, you use a text editor to create what is called a source code file. This file contains the C rendition of your program design. 

#include <stdio.h>
int main(void)
{
    int dogs;

    printf("How many dogs do you have?\n");
    scanf("%d", &dogs);
    printf("So you have %d dog(s)!\n", dogs);

    return 0;
}


As part of this step, you should document your work. The simplest way is to use C’s comment facility to incorporate explanations into your source code. 

 

Step 4: Compile


The next step is to compile the source code. Again, the details depend on your programming environment, and we’ll look at some common environments shortly. For now, let’s start with a more conceptual view of what happens.

Recall that the compiler is a program whose job is to convert source code into executable code. Executable code is code in the native language, or machine language , of your computer. This language consists of detailed instructions expressed in a numeric code. As you read earlier, different computers have different machine languages, and a C compiler translates C into a
particular machine language. C compilers also incorporate code from C libraries into the final program; the libraries contain a fund of standard routines, such as printf() and scanf() , for your use. (More accurately, a program called a linker brings in the library routines, but the compiler runs the linker for you on most systems.) The end result is an executable file containing
code that the computer understands and that you can run. The compiler also checks that your program is valid C. If the compiler finds errors, it reports them to you and doesn’t produce an executable file. Understanding a particular compiler’s
complaints is another skill you will pick up.

 

 

Step 5: Run the Program


Traditionally, the executable file is a program you can run. To run the program in many common environments, including Windows Command-Prompt mode, Unix terminal mode, and Linux terminal mode, just type the name of the executable file. Other environments, such as VMS on a VAX, might require a run command or some other mechanism. Integrated development
environments (IDEs) , such as those provided for Windows and Macintosh environments, allow you to edit and execute your C program from within the IDE by selecting choices from a menu or by pressing special keys. The resulting program also can be run directly from the operating system by clicking or double-clicking the filename or icon.


Step 6: Test and Debug the Program


The fact that your program runs is a good sign, but it’s possible that it could run incorrectly. Consequently, you should check to see that your program does what it is supposed to do. You’ll find that some of your programs have mistakes— bugs , in computer jargon. Debugging is the process of finding and fixing program errors. Making mistakes is a natural part of learning.
It seems inherent to programming, so when you combine learning and programming, you had best prepare yourself to be reminded often of your fallibility. As you become a more powerful and subtle programmer, your errors, too, will become more powerful and subtle.

You have many opportunities to err. You can make a basic design error. You can implement good ideas incorrectly. You can overlook unexpected input that messes up your program. You can use C incorrectly. You can make typing errors. You can put parentheses in the wrong place, and so on. You’ll find your own items to add to this list.

Fortunately, the situation isn’t hopeless, although there might be times when you think it is. The compiler catches many kinds of errors, and there are things you can do to help yourself track down the ones that the compiler doesn’t catch. This book will give you debugging advice as you go along.

 

Step 7: Maintain and Modify the Program


When you create a program for yourself or for someone else, that program could see extensive use. If it does, you’ll probably find reasons to make changes in it. Perhaps there is a minor bug that shows up only when someone enters a name beginning with Zz , or you might think of a better way to do something in the program. You could add a clever new feature. You might
adapt the program so that it runs on a different computer system. All these tasks are greatly simplified if you document the program clearly and if you follow sound design practices.


Commentary


Programming is not usually as linear as the process just described. Sometimes you have to go back and forth between steps. For instance, when you are writing code, you might find that your plan was impractical. You may see a better way of doing things or, after you see how a program runs, you might feel motivated to change the design. Documenting your work helps
you move back and forth between levels.
Most learners tend to neglect steps 1 and 2 (defining program objectives and designing the program) and go directly to step 3 (writing the program). The first programs you write are simple enough that you can visualize the whole process in your head. If you make a mistake, it’s easy to find. As your programs grow longer and more complex, mental visualizations begin
to fail, and errors get harder to find. Eventually, those who neglect the planning steps are condemned to hours of lost time, confusion, and frustration as they produce ugly, dysfunctional, and abstruse programs. The larger and more complex the job is, the more planning it requires.
The moral here is that you should develop the habit of planning before coding. Use the ancient but honorable pen-and-pencil technology to jot down the objectives of your program and to outline the design. If you do so, you eventually will reap substantial dividends in time saved and satisfaction gained.

 

 

Programming Mechanics

 

The exact steps you must follow to produce a program depend on your computer environment. Because C is portable, it’s available in many environments, including Unix, Linux, MS-DOS(yes, some people still use it), Windows, and Macintosh OS. There’s not enough space in thisbook to cover all environments, particularly because particular products evolve, die, and are
replaced.
First, however, let’s look at some aspects shared by many C environments, including the five we just mentioned. You don’t really need to know what follows to run a C program, but it is good background. It can also help you understand why you have to go through some particular steps to get a C program.
When you write a program in the C language, you store what you write in a text file called a source code file . Most C systems, including the ones we mentioned, require that the name ofthe file end in .c (for example, wordcount.c and budget.c ). The part of the name before the period is called the basename , and the part after the period is called the extension . Therefore, budget is a basename and c is the extension. The combination budget.c is the filename. The name should also satisfy the requirements of the particular computer operating system. For example, MS-DOS is an older operating system for IBM PCs and clones. It requires that the basename be no more than eight characters long, so the wordcount.c filename mentioned earlier would not be a valid DOS filename. Some Unix systems place a 14-character limit on the whole name, including the extension; other Unix systems allow longer names, up to 255 characters. Linux, Windows, and Macintosh OS also allow long names.
 

Object Code Files, Executable Files, and Libraries


The basic strategy in C programming is to use programs that convert your source code file to an executable file, which is a file containing ready-to-run machine language code. C implementations typically do this in two steps: compiling and linking. The compiler converts your source code to an intermediate code, and the linker combines this with other code to produce the executable file. C uses this two-part approach to facilitate the modularization of programs. You can compile individual modules separately and then use the linker to combine the compiled modules later. That way, if you need to change one module, you don’t have to recompile the other ones. Also, the linker combines your program with precompiled library code.
There are several choices for the form of the intermediate files. The most prevalent choice, and the one taken by the implementations described here, is to convert the source code to machine language code, placing the result in an object code file , or object file for short. (This assumes that your source code consists of a single file.) Although the object file contains machine language code, it is not ready to run. The object file contains the translation of your source code, but it is
not yet a complete program.
The first element missing from the object code file is something called startup code , which is code that acts as an interface between your program and the operating system. For example,you can run an IBM PC compatible under MS Windows or under Linux. The hardware is the same in either case, so the same object code would work with both, but you would need different startup code for Windows than you would for Linux because these systems handle programs differently from one another.
The second missing element is the code for library routines. Nearly all C programs make use of routines (called functions ) that are part of the standard C library. For example, concrete.c uses the function printf() . The object code file does not contain the code for this function; it merely contains instructions saying to use the printf() function. The actual code is stored in another file, called a library . A library file contains object code for many functions.
The role of the linker is to bring together these three elements—your object code, the standard
startup code for your system, and the library code—and put them together into a single file, the
executable file. For library code, the linker extracts only the code needed for the functions you
use from the library (see Figure 1.4 ).

 

In short, an object file and an executable file both consist of machine language instructions. However, the object file contains the machine language translation only for the code you used, but the executable file also has machine code for the library routines you use and for the startup code.

 

Command-Line Compilers for the PC


C compilers are not part of the standard Windows package, so you may need to obtain and install a C compiler. Cygwin and MinGW are free downloads that make the GCC compiler available for command-line use on a PC. Cygwin runs in its own window, which has a Command-Prompt look but which imitates a Linux command-line environment. MinGW, on the other hand runs in the Windows Command-Prompt mode. These come with the newest (or near-newest) version of GCC, which supports C99 and at least some of C11. The Borland C++ Compiler 5.5 is another free download; it supports C90. Source code files should be text files, not word processor files. (Word processor files contain a lot of additional information about fonts and formatting.) You should use a text editor, such as Windows Notepad. You can use a word processor if you use the Save As feature to save the file in text mode. The file should have a .c extension. Some word processors automatically add a .txt extension to text files. If this happens to you, you need to change the filename, replacing txt with c .
C compilers for the PC typically, but not always, produce intermediate object code files having an .obj extension. Unlike Unix compilers, these compilers typically don’t remove these files when done. Some compilers produce assembly language files with .asm extensions or use some special format of their own.
Some compilers run the linker automatically after compiling; others might require that you run the linker manually. Linking results in the executable file, which appends the .EXE extension to the original source code basename. For example, compiling and linking a source code file called concrete.c produces a file called concrete.exe . You can run the program by typing
the basename at the command line:
 

C>concrete

 

Summary

 

C is a powerful, concise programming language. It is popular because it offers useful programming tools, good control over hardware, and because C programs are easier than most to transport from one system to another.
C is a compiled language. C compilers and linkers are programs that convert C language source code into executable code.
Programming in C can be taxing, difficult, and frustrating, but it can also be intriguing, exciting, and satisfying. We hope you find it as enjoyable and fascinating as we do.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九成宫醴泉铭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值