BUY THIS BOOK
Add to Cart

Print Book $34.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint this content?


Practical C Programming
Practical C Programming, Third Edition By Steve Oualline
August 1997
Pages: 454

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: What Is C?
Profanity is the one language that all programmers understand.
—Anon.
The ability to organize and process information is the key to success in the modern age. Computers are designed to handle and process large amounts of information quickly and efficiently, but they can't do anything until someone tells them what to do.
That's where C comes in. C is a programming language that allows a software engineer to efficiently communicate with a computer.
C is a highly flexible and adaptable language. Since its creation in 1970, it's been used for a wide variety of programs including firmware for micro-controllers, operating systems, applications, and graphics programming.
C is one of the most most widely used languages in the world and is fairly stable. An improved C language called C++ has been invented, but it is still in development, and its definition is still being worked on. C++, originally known as C with Classes, adds a number of new features to the C language, the most important of which is the class. Classes facilitate code reuse through object-oriented design (OOD).
Which is better, C or C++? The answer depends on who you talk to. C++ does great things for you behind your back, such as automatically calling constructors and destructors for variables. This processing makes some types of programming easy, but it makes static checking of programs difficult, and you need to be able to tell exactly what your program is doing if you are working on embedded control applications. So some people consider C++ the better language because it does things automatically and C doesn't. Other people consider C better for precisely the same reason.
Also, C++ is a relatively new language that's still changing. Much more C code exists than C++ code, and that C code will need to be maintained and upgraded. So C will be with us for a long time to come.
Communicating with computers is not easy. They require instructions that are exact and detailed. It would be nice if we could write programs in English. Then we could tell the computer, "Add up all my checks and deposits, then tell me the total," and the machine would balance our checkbook.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Programming Works
Communicating with computers is not easy. They require instructions that are exact and detailed. It would be nice if we could write programs in English. Then we could tell the computer, "Add up all my checks and deposits, then tell me the total," and the machine would balance our checkbook.
But English is a lousy language when it comes to writing exact instructions. The language is full of ambiguity and imprecision. Grace Hopper, the grand old lady of computing, once commented on the instructions she found on a bottle of shampoo:
Wash
Rinse
Repeat
She tried to follow the directions, but she ran out of shampoo. (Wash-Rinse-Repeat. Wash-Rinse-Repeat. Wash-Rinse-Repeat...)
Of course, we can try to write in precise English. We'd have to be careful and make sure to spell everything out and be sure to include instructions for every contingency. But if we worked really hard, we could write precise English instructions.
It turns out that there is a group of people who spend their time trying to write precise English. They're called the government, and the documents they write are called government regulations. Unfortunately, in their effort to make the regulations precise, the government has made them almost unreadable. If you've ever read the instruction book that comes with your tax forms, you know what precise English can be like.
Still, even with all the extra verbiage that the government puts in, problems can occur. A few years ago California passed a law requiring all motorcycle riders to wear a helmet. Shortly after this law went into effect, a cop stopped a guy for not wearing one. The man suggested the policeman take a closer look at the law.
The law had two requirements: 1) that motorcycle riders have an approved crash helmet and 2) that it be firmly strapped on. The cop couldn't give the motorcyclist a ticket because he did have a helmet firmly strapped on—to his knee.
So English, with all its problems, is out. Now, how do we communicate with a computer?
The first computers cost millions of dollars, while at the same time a good programmer cost about $15,000 a year. Programmers were forced to program in a language in which all the instructions were reduced to a series of numbers, called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Brief History of C
In 1970 a programmer, Dennis Ritchie, created a new language called C. (The name came about because it superceded the old programming language he was using: B.) C was designed with one goal in mind: writing operating systems. The language was extremely simple and flexible, and soon was used for many different types of programs. It quickly became one of the most popular programming languages in the world.
C's popularity was due to two major factors. The first was that the language didn't get in the way of the programmer. He could do just about anything by using the proper C construct. (As we will see, this flexibility is also a drawback, as it allows the program to do things that the programmer never intended.)
The second reason that C is popular is that a portable C compiler was widely available. Consequently, people could attach a C compiler for their machine easily and with little expense.
In 1980, Bjarne Stroustrup started working on a new language, called "C with Classes." This language improved on C by adding a number of new features. This new language was improved and augmented, and finally became C++.
One of the newest languages, Java, is based on C++. Java was designed to be "C++ with the bugs fixed." At the time of this writing, Java has limited use despite being heavily marketed by Sun Microsystems and others.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How C Works
C is designed as a bridge between the programmer and the raw computer. The idea is to let the programmer organize a program in a way that he can easily understand. The compiler then translates the language into something that the machine can use.
Computer programs consist of two main parts: data and instructions. The computer imposes little or no organization on these two parts. After all, computers are designed to be as general as possible. The programmer should impose his organization on the computer, not the other way around.
The data in a computer is stored as a series of bytes. C organizes those bytes into useful data. Data declarations are used by the programmer to describe the information he is working with. For example:
int total;	    /* Total number accounts */
tells C that we want to use a section of the computer's memory to store an integer named total. We let the compiler decide what particular bytes of memory to use; that decision is a minor bookkeeping detail that we don't want to worry about.
Our variable total is a simple variable. It can hold only one integer and describe only one total. A series of integers can be organized into an array as follows:
int balance[100];   /* Balance (in cents) for all 100 accounts */
Again, C will handle the details of imposing that organization on the computer's memory. Finally, there are more complex data types. For example, a rectangle might have a width, a height, a color, and a fill pattern. C lets us organize these four items into one group called a structure.
struct rectangle {
    int width;        /* Width of rectangle in pixels */
    int height;       /* Height of rectangle in pixels */
    color_type color; /* Color of the rectangle */
    fill_type fill;   /* Fill pattern */
};
The point is that structures allow the programmer to arrange the data to suit his needs no matter how simple or complex that data is. Translation of this data description into something the computer can use is the job of the compiler, not the programmer.
But data is only one part of a program. We also need instructions. As far as the computer is concerned, it knows nothing about the layout of the instructions. It knows what it's doing for the current instruction and where to get the next one, but nothing more.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How to Learn C
There is only one way to learn how to program and that is to write programs. You'll learn a lot more by writing and debugging programs than you ever will by reading this book. This book contains many programming exercises. You should try to do as many of them as possible. When you do the exercises, keep good programming style in mind. Always comment your programs, even if you're only doing the exercises for yourself. Commenting helps you organize your thoughts and keeps you in practice when you go into the real world.
Don't let yourself be seduced by the idea that "I'm only writing these programs for myself, so I don't need to comment them." First of all, code that looks obvious to a programmer as he writes it is often confusing and cryptic when he revisits it a week later. Writing comments also helps you to get organized before you write the actual code. (If you can write out an idea in English, you're halfway to writing it in C.)
Finally, programs tend to be around far longer than expected. I once wrote a program that was designed to work only on the computer at Caltech. The program was highly system-dependent. Because I was the only one who would ever use it, the program would print the following message if you got the command line wrong:
?LSTUIT User is a twit
A few years later, I was a student at Syracuse University, and the Secretary at the School of Computer Science needed a program that was similar to my Caltech listing program. So I adapted my program for her use. Unfortunately, I forgot about the error message.
Imagine how horrified I was when I came into the Computer Science office and was accosted by the Chief Secretary. This lady had so much power that she could make the Dean cringe. She looked at me and said, "User is a twit, huh!" Luckily she had a sense of humor, or I wouldn't be here today.
Sprinkled throughout this book are many broken programs. Spend the time to figure out why they don't work. Often, the problem is very subtle, such as a misplaced semicolon or the use of = instead of ==. These programs let you learn how to spot mistakes in a small program. Then, when you make similar mistakes in a big program, and you
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Basics of Program Writing
The first and most important thing of all, at least for writers today, is to strip language clean, to lay it bare down to the bone.
—Ernest Hemingway
Programs start as a set of instructions written by a human being. Before they can be used by the computer, they must undergo several transformations. In this chapter, we'll learn how to enter a program, transform it into something the machine can use, and run it. Detailed steps are provided for the most popular UNIX and DOS/Windows compilers.
C programs are written in a high-level language using letters, numbers, and the other symbols you find on a computer keyboard. Computers actually execute a very low-level language called machine code (a series of numbers). So, before a program level can be used, it must undergo several transformations.
Programs start out as an idea in a programmer's head. He uses a text editor to write his thoughts into a file called a source file, containing source code. This file is transformed by the compiler into an object file. Next, a program called the linker takes the object file, combines it with predefined routines from a standard library, and produces an executable program (a set of machine-language instructions). In the following sections, we'll see how these various forms of the program work together to produce the final program.
Figure 2-1 shows the steps that must be taken to transform a program written in a high-level language into a executable program.
Figure 2-1: Transformation of a high-level language into a program
Fortunately you don't have to run the compiler, assembler, and linker individually. Most C compilers use "wrapper" programs that determine which tools need to be run and then run them.
Some programming systems go even further and provide the developer with an Integrated Development Environment (IDE). The IDE contains an editor, compiler, linker, project manager, debugger, and more in one convenient package. Both Borland and Microsoft provide IDEs with their compilers.
Before we can actually start creating our own programs, we need to know how to use the basic programming tools. In this section, we will take you step by step through the process of entering, compiling, and running a simple program.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Programs from Conception to Execution
C programs are written in a high-level language using letters, numbers, and the other symbols you find on a computer keyboard. Computers actually execute a very low-level language called machine code (a series of numbers). So, before a program level can be used, it must undergo several transformations.
Programs start out as an idea in a programmer's head. He uses a text editor to write his thoughts into a file called a source file, containing source code. This file is transformed by the compiler into an object file. Next, a program called the linker takes the object file, combines it with predefined routines from a standard library, and produces an executable program (a set of machine-language instructions). In the following sections, we'll see how these various forms of the program work together to produce the final program.
Figure 2-1 shows the steps that must be taken to transform a program written in a high-level language into a executable program.
Figure 2-1: Transformation of a high-level language into a program
Fortunately you don't have to run the compiler, assembler, and linker individually. Most C compilers use "wrapper" programs that determine which tools need to be run and then run them.
Some programming systems go even further and provide the developer with an Integrated Development Environment (IDE). The IDE contains an editor, compiler, linker, project manager, debugger, and more in one convenient package. Both Borland and Microsoft provide IDEs with their compilers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Real Program
Before we can actually start creating our own programs, we need to know how to use the basic programming tools. In this section, we will take you step by step through the process of entering, compiling, and running a simple program.
We will describe how to use two different types of compilers. The first type is the standalone or command-line compiler. This type of compiler is operated in a batch mode from the command line. In other words, you type in a command, and the compiler turns your source code into an executable program.
The other type of compiler is contained in an IDE. The IDE contains an editor, compiler, project manager, and debugger in one package.
Most UNIX systems use command-line compilers. There are a few IDE compilers available for UNIX, but they are rare. On the other hand, almost every compiler for MS-DOS/Windows contains an IDE. For the command-line die-hards, these compilers do contain a command-line compiler as well.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Program Using a Command-Line Compiler
In this section, we'll go through the step-by-step process needed to create a program using a command-line compiler. Instructions are provided for a generic UNIX compiler (cc), the Free Software Foundation's gcc compiler, Turbo C++, Borland C++, and Microsoft Visual C++.
However, if you are using a Borland or Microsoft compiler, you might want to skip ahead to the section on using the IDE.
You can more easily manage things if you create a separate directory for each program that you're working on. In this case, we'll create a directory called hello to hold our hello program.
On UNIX type:
% mkdir hello
% cd hello
On MS-DOS type:
C:> MKDIR HELLO
C:> CD HELLO
A program starts out as a text file. Example 2-1 shows our program in source form.
Example 2-1. hello/hello.c
[File: hello/hello.c]
#include <stdio.h>
int main()
{
    printf("Hello World\n");
    return (0);
}
Use your favorite text editor to enter the program. Your file should be named hello.c.
MS-DOS/Windows users should not use a word processor such as MS-Word or WordPerfect to write their programs. Word processors add formatting codes to files, which confuse the compiler. You must use a text editor such as the MS-DOS "EDIT" program that is capable of editing ASCII files.
The compiler takes the source file you've just made and converts it into an executable program. Each compiler has a different command line. The commands for the most popular compilers are listed below.

Section 2.3.3.1: UNIX cc compiler (generic UNIX)

Most UNIX-based compilers follow the same generic standard. The C compiler is named cc, and to compile our hello program we need the following command:
% cc -g -ohello hello.c
The -g option enables debugging. (The compiler adds extra information to the program to make the program easier to debug.) The switch -ohello tells the compiler that the program is to be called hello, and the final hello.c is the name of the source file. See your compiler manual for details on all the possible options. There are several different C compilers for UNIX, so your command line may be slightly different.

Section 2.3.3.2: Free Software Foundation's gcc compiler

Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Program Using an Integrated Development Environment
Integrated Development Environments (IDEs) provide a one-stop shop for programming. They take a compiler, editor, and debugger and wrap them into one neat package for the program.
You can more easily manage things if you create a separate directory for each program that you're working on. In this case, we'll create a directory called HELLO to hold our hello program.
On MS-DOS type:
C:> MKDIR HELLO
C:> CD HELLO
Each IDE is a little different, so we've included separate instructions for each one.

Section 2.4.2.1: Turbo C++

  1. Start the Turbo C++ IDE with the command:
    C:> TC
  2. Select the Window|Close All menu item to clear the desktop of any old windows. We'll want to start clean. The screen should look like Figure 2-2.
    Figure 2-2: Clean desktop
  3. Select the Options|Compiler|Code Generation menu item to pull up the Code Generation dialog as seen in Figure 2-3. Change the memory model to Large.
    Figure 2-3: Code Generation dialog
  4. Select the Options|Compiler|Entry/Exit menu item and turn on "Test stack overflow" as seen in Figure 2-4.
    Figure 2-4: Entry/Exit Code Generation dialog
  5. Select the Options|Compiler|Messages|Display menu item to bring up the Compiler Messages dialog as seen in Figure 2-5. Select All to display all the warning messages.
    Figure 2-5: Compiler Messages dialog
  6. Select the Options|Save menu item to save all the options we've used so far.
  7. Select the Project|Open menu item to select a project file. In this case, our project file is called HELLO.PRJ. The screen should look like Figure 2-6 when you're done.
    Figure 2-6: Open Project File dialog
  8. Press the INSERT key to add a file to the project. The file we want to add is HELLO.C as seen in Figure 2-7.
    Figure 2-7: Add to Project List dialog
  9. Press ESC to get out of the add-file cycle.
  10. Press UP-ARROW to go up one line. The line with HELLO.C should now be highlighted as seen in Figure 2-8.
    Figure 2-8: Hello project
  11. Press ENTER to edit this file.
  12. Enter Example 2-2.
    Example 2-2. hello/hello.c
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Help on UNIX
Most UNIX systems have an online documentation system called the manpages. These manpages can be read with the man command. (UNIX uses man as an abbreviation for manual.) To get information about a particular subject, use the following command:
man subject
For example, to find out about the classes defined in the printf function, you would type:
man printf
The command also has a keyword search mode:
man -k keyword
To determine the name of manpage with the word "output" in its title, use the command:
man -k output
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Help in an Integrated Development Environment
IDEs such as Turbo C++, Borland C++, and Microsoft C++ have a Help menu item. This item activates a hypertext-based help system.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
IDE Cookbooks
This section contains a brief summary of the commands used to enter, compile, and execute a simple program using the three IDEs described in this chapter.
1.
Window|Close All
Clean out any old junk.
2.
Options|Compiler|Code Generation
Memory Model = Large
For simple program, use large memory model.
3.
Options|Compiler|Entry/Exit
Test stack overflow = On
Turn on test for a common programming error.
4.
Options|Compiler|Messages|Display
Display warnings = All
Tell compiler that you want all diagnostics that it can give you.
5.
Options|Save
Save options.
6.
Project|Open
Project file = program.PRJ
Create a new project.
7.
Insert
Add file program.c
Add program file to project.
8.
ESC
Get out of "add-file" cycle.
9.
UP-ARROW
Move to program.c line.
10.
RETURN
Edit program file.
11.
Type in the program
Enter text of program.
12.
Run|Run
Execute program.
13.
Window|User
Display results of the program.
14.
File|Save
Save the program.
15.
File|Quit
Exit Turbo C++ IDE.
1.
Window|Close All
Clean out any old junk.
2.
Project|New Project
Project Path and Name = c.\ program\program.ide
Target Type = EasyWin(.exe)
Target Model = Large
Create new project.
3.
Click on Advanced button
Set .c Node
Clear .rc and .def
Setup a simple C program.
4.
Click on OK
Return to New Target window.
5.
Click on OK
Return to main window.
6.
ALT-F10
Select node submenu.
7.
Edit|Node Attributes
Style Sheet = Debug Info and Diagnostics
Turn on debugging.
8.
Click on OK button
Return to main menu.
9.
Options|Project Options
Click on + under Compiler
Test stack overflow = On
Turn on valuable run-time test.
10.
Click on OK button
Save options.
11.
Click on OK button
Return to main window.
12.
DOWN-ARROW
Move to program[.c] line.
13.
RETURN
Edit program file.
14.
Type in the program
Enter text of program.
15.
Debug|Run
Run program.
1.
Window|Close All
Clean out any old junk.
2.
Project|New
Project Name = \program\program.mak
Project Type =
QuickWin application (.EXE)
Start project.
Set up project.
Click on OK button.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Programming Exercises
Exercise 2-1: On your computer, type in the hello program and execute it.
Exercise 2-2: Take several programming examples from any source, enter them into the computer, and run them.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Style
There is no programming language, no matter how structured, that will prevent programmers from writing bad programs.
—L. Flon
It is the nobility of their style which will make our writers of 1840 unreadable forty years from now.
—Stendhal
This chapter discusses how to use good programming style to create a simple, easy-to-read program. Discussing style before we know how to program might seem backward, but style is the most important part of programming. Style is what separates the gems from the junk. It is what separates the programming artist from the butcher. You must learn good programming style first, before typing in your first line of code, so that everything you write will be of the highest quality.
Contrary to popular belief, programmers do not spend most of their time writing programs. Far more time is spent maintaining, upgrading, and debugging existing code than is ever spent on creating new works. According to Datamation, the amount of time spent on maintenance is skyrocketing. From 1980 to 1990, the average number of lines in a typical application went from 23,000 to 1,200,000. The average system age went from 4.75 to 9.4 years.
What's worse, 74% of the managers surveyed at the 1990 Annual Meeting and Conference of the Software Maintenance Association reported that they "have systems in their department, that have to be maintained by specific individuals because no one else understands them."
Most software is built on existing software. I recently completed the code for 12 new programs. Only one of these was created from scratch; the other 11 are adaptations of existing programs.
Some programmers believe that the purpose of a program is only to present the computer with a compact set of instructions. This concept is not true. Programs written only for the machine have two problems:
  • They are difficult to correct because sometimes even the author does not understand them.
  • Modifications and upgrades are difficult to make because the maintenance programmer must spend a considerable amount of time figuring out what the program does from its code. Ideally, a program serves two purposes: first, it presents the computer with a set of instructions, and second, it provides the programmer with a clear, easy-to-read description of what the program does.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Common Coding Practices
A variable is a place in the computer's memory for storing a value. C identifies that place by the variable name. Names can be of any length and should be chosen so their meanings are clear. (Actually, a length limit exists, but it is so large that you probably will never encounter it.) Every variable in C must be declared. Variable declarations will be discussed in Chapter 9. The following declaration tells C that we're going to use three integer (int) variables: p, q, and r:
int p,q,r;
But what are these variables for? The reader has no idea. They could represent the number of angels on the head of a pin or the location and acceleration of a plasma bolt in a game of Space Invaders. Avoid abbreviations. Exs. abb. are diff. to rd. and hd. to ustnd. (Excess abbreviations are difficult to read and hard to understand.)
Now consider another declaration:
int account_number; 
int balance_owed;
Now we know that we're dealing with an accounting program, but we could still use some more information. For example, is the balance_owed in dollars or cents? We should have added a comment after each declaration to explain what we were doing. For example:
int account_number;      /* Index for account table */ 
int balance_owed;        /* Total owed us (in pennies)*/
By putting a comment after each declaration, we, in effect, create a mini-dictionary where we define the meaning of each variable name. Because the definition of each variable is in a known place, it's easy to look up the meaning of a name. (Programming tools like editors, cross-referencers, and searching tools such as grep can also help you quickly find a variable's definition.)
Units are very important. I was once asked to modify a program that converted plot data files from one format to another. Many different units of length were used throughout the program, and none of the variable declarations were commented. I tried very hard to figure out what was going on, but I could not determine what units were being used in the program. Finally, I gave up and put the following comment in the program:
/******************************************************** 
 * Note:  I have no idea what the input units are, nor  * 
 *      do I have any idea what the output units are,   * 
 *      but I have discovered that if I divide by 3     * 
 *      the plot sizes look about right.                * 
 ********************************************************/
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Coding Religion
Computer scientists have devised many programming styles. These include structured programming, top-down programming, goto-less programming, and object-oriented design (OOD). Each of these styles has its own following or cult. I use the term "religion" because people are taught to follow the rules blindly without knowing the reasons behind them. For example, followers of the goto-less cult will never use a goto statement, even when it is natural to do so.
The rules presented in this book result from years of programming experience. I have discovered that by following these rules, I can create better programs. You do not have to follow them blindly. If you find a better system, by all means use it. (If your solution really works, drop me a line. I'd like to use it too.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Indentation and Code Format
In order to make programs easier to understand, most programmers indent their programs. The general rule for a C program is to indent one level for each new block or conditional. In our previous example, there are three levels of logic, each with its own indentation level. The while statement is outermost. The statements inside the while are at the next level. Finally, the statement inside the if (break) is at the innermost level.
There are two styles of indentation, and a vast religious war is being raged in the programming community as to which style is better. The first is the short form:
while (! done) { 
    printf("Processing\n"); 
    next_entry(); 
} 
if (total <= 0) { 
    printf("You owe nothing\n"); 
    total = 0; 
} else { 
    printf("You owe %d dollars\n", total); 
    all_totals = all_totals + total; 
}
In this case, curly braces ({}) are put on the same line as the statements. The other style puts the {} on lines by themselves:
while (! done)  
{ 
    printf("Processing\n"); 
    next_entry(); 
} 
if (total <= 0)  
{ 
   printf("You owe nothing\n"); 
   total = 0; 
} 
else  
{ 
   printf("You owe %d dollars\n", total); 
   all_totals = all_totals + total; 
}
Both formats are frequently used. You should use the format you feel most comfortable with. This book uses the short format because it's more compact and therefore saves book space.
The amount of indentation is left to the programmer. Two, four, and eight spaces are common. Studies have shown that a four-space indent makes the code most readable. However, being consistent in your indentation is far more important than the indention size you use.
Some editors, like the UNIX Emacs editor, the Turbo C++, Borland C++, and Microsoft Visual C++ internal editors, contain code that automatically indents your programs as you create them. Although these editor-based indentation systems are not perfect, they do go a long way to helping you create properly formatted code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Clarity
A program should read like a technical paper. It should be organized into sections and paragraphs. Procedures form a natural section boundary. (We'll learn about function in Chapter 9.) You must organize your code into paragraphs. You should begin a paragraph with a topic-sentence comment and separate the comment from other paragraphs with a blank line. For example:
/* poor programming practice */ 
temp = box_x1; 
box_x1 = box_x2; 
box_x2 = temp; 
temp = box_y1; 
box_y1 = box_y2; 
box_y2 = temp;
A better version would be:
/* 
 * Swap the two corners  
 */ 

/* Swap X coordinate */ 
temp = box_x1; 
box_x1 = box_x2; 
box_x2 = temp; 

/* Swap Y coordinate */ 
temp = box_y1; 
box_y1 = box_y2; 
box_y2 = temp;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simplicity
Your program should be simple. Some general rules of thumb are:
  • A single function should not be longer than two or three pages. (See Chapter 9.) If the function gets longer, it can probably be split into two simpler functions. This rule comes about because the human mind can only hold so much in short-term memory. Three pages are about the most that the human mind can wrap itself around in one sitting.
    Also if your function goes beyond the three-page limit, it probably doesn't define a single operation, or probably contains too much detail.
  • Avoid complex logic like multiply nested ifs. The more complex your code, the more indentation levels you will need. When you start running into the right margin, you should consider splitting your code into multiple procedures, to decrease the level of complexity.
  • Did you ever read a sentence, like this one, in which the author went on and on, stringing together sentence after sentence with the word "and," and didn't seem to understand the fact that several shorter sentences would do the job much better, and didn't it bother you? C statements should not go on forever. Long statements should be avoided. If it looks like an equation or formula is going to be longer than one or two lines, you should split it into two shorter equations.
  • Finally, the most important rule: make your program as simple and easy to understand as possible, even if you must break some of the rules. The goal is clarity, and the rules given in this chapter are designed to help you accomplish that goal. If they get in the way, get rid of them. I have seen one program with a single statement that spanned over 20 pages; however, because of the specialized nature of the program, this statement was simple and easy to understand.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
A program should be concise and easy to read. It must serve as a set of computer instructions, but also as a reference work describing the algorithms and data used inside it. Everything should be documented with comments. Comments serve two purposes. First, they tell the programmer to follow the code, and second, they help the programmer remember what he did.
Class discussion: Create a style sheet for class assignments. Discuss what comments should go into the programs and why.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Basic Declarations and Expressions
A journey of a thousand miles must begin with a single step.
—Lao-zi
If carpenters made buildings the way programmers make programs, the first woodpecker to come along would destroy all of civilization.
—Weinberg's Second Law
If you are going to construct a building, you need two things: the bricks and a blueprint that tells you how to put them together. In computer programming, you need two things: data (variables) and instructions (code or functions). Variables are the basic building blocks of a program. Instructions tell the computer what to do with the variables.
Comments are used to describe the variables and instructions. They are notes by the author documenting the program so that the program is clear and easy to read. Comments are ignored by the computer.
In construction, before we can start, we must order our materials: "We need 500 large bricks, 80 half-size bricks, and 4 flagstones." Similarly, in C, we must declare our variables before we can use them. We must name each one of our "bricks" and tell C what type of brick to use.
After our variables are defined, we can begin to use them. In construction, the basic structure is a room. By combining many rooms, we form a building. In C, the basic structure is a function. Functions can be combined to form a program.
An apprentice builder does not start out building the Empire State Building, but rather starts on a one-room house. In this chapter, we will concentrate on constructing simple one-function programs.
The basic elements of a program are the data declarations, functions, and comments. Let's see how these can be organized into a simple C program.
The basic structure of a one-function program is:
/**************************************************** 
 * ...Heading comments...                            * 
 ****************************************************/ 
...Data declarations...
int main() 
{ 
    ...Executable statements... 
    return (0); 
}
Heading comments tell the programmer about the program, and data declarations describe the data that the program is going to use.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Elements of a Program
If you are going to construct a building, you need two things: the bricks and a blueprint that tells you how to put them together. In computer programming, you need two things: data (variables) and instructions (code or functions). Variables are the basic building blocks of a program. Instructions tell the computer what to do with the variables.
Comments are used to describe the variables and instructions. They are notes by the author documenting the program so that the program is clear and easy to read. Comments are ignored by the computer.
In construction, before we can start, we must order our materials: "We need 500 large bricks, 80 half-size bricks, and 4 flagstones." Similarly, in C, we must declare our variables before we can use them. We must name each one of our "bricks" and tell C what type of brick to use.
After our variables are defined, we can begin to use them. In construction, the basic structure is a room. By combining many rooms, we form a building. In C, the basic structure is a function. Functions can be combined to form a program.
An apprentice builder does not start out building the Empire State Building, but rather starts on a one-room house. In this chapter, we will concentrate on constructing simple one-function programs.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Program Structure
The basic elements of a program are the data declarations, functions, and comments. Let's see how these can be organized into a simple C program.
The basic structure of a one-function program is:
/**************************************************** 
 * ...Heading comments...                            * 
 ****************************************************/ 
...Data declarations...
int main() 
{ 
    ...Executable statements... 
    return (0); 
}
Heading comments tell the programmer about the program, and data declarations describe the data that the program is going to use.
Our single function is named main. The name main is special, because it is the first function called. Other functions are called directly or indirectly from main. The function main begins with:
int main() 
{
and ends with:
return (0); 
}
The line return(0); is used to tell the operating system (UNIX or MS-DOS/Windows) that the program exited normally (Status=0). A nonzero status indicates an error—the bigger the return value, the more severe the error. Typically, a status of 1 is used for the most simple errors, like a missing file or bad command-line syntax.
Now, let's take a look at our Hello World program (Example 3-1).
At the beginning of the program is a comment box enclosed in /* and */. Following this box is the line:
#include <stdio.h>
This statement signals C that we are going to use the standard I/O package. The statement is a type of data declaration. Later we use the function printf from this package.
Our main routine contains the instruction:
printf("Hello World\n");
This line is an executable statement instructing C to print the message "Hello World" on the screen. C uses a semicolon (;) to end a statement in much the same way we use a period to end a sentence. Unlike line-oriented languages such as BASIC, an end-of-line does not end a statement. The sentences in this book can span several lines—the end of a line is treated just like space between words. C works the same way. A single statement can span several lines. Similarly, you can put several sentences on the same line, just as you can put several C statements on the same line. However, most of the time your program is more readable if each statement starts on a separate line.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simple Expressions
Computers can do more than just print strings—they can also perform calculations. Expressions are used to specify simple computations. The five simple operators in C are listed in Table 4-1.
Table 4-1: Simple Operators
Operator
Meaning
*
Multiply
/
Divide
+
Add
-
Subtract
%
Modulus (return the remainder after division)
Multiply (*), divide (/), and modulus (%) have precedence over add (+) and subtract (-). Parentheses, ( ), may be used to group terms. Thus:
(1 + 2) * 4
yields 12, while:
1 + 2 * 4
yields 9.
Example 4-1 computes the value of the expression (1 + 2) * 4.
Example 4-1. simple/simple.c
int main()
{
    (1 + 2) * 4;
    return (0);
}
Although we calculate the answer, we don't do anything with it. (This program will generate a "null effect" warning to indicate that there is a correctly written, but useless, statement in the program.)
Think about how confused a workman would be if we were constructing a building and said,
"Take your wheelbarrow and go back and forth between the truck and the building site."
"Do you want me to carry bricks in it?"
"No. Just go back and forth."
We need to store the results of our calculations.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables and Storage
C allows us to store values in variables. Each variable is identified by a variable name.
In addition, each variable has a variable type. The type tells C how the variable is going to be used and what kind of numbers (real, integer) it can hold. Names start with a letter or underscore ( _ ), followed by any number of letters, digits, or underscores. Uppercase is different from lowercase, so the names sam, Sam, and SAM specify three different variables. However, to avoid confusion, you should use different names for variables and not depend on case differences.
Nothing prevents you from creating a name beginning with an underscore; however, such names are usually reserved for internal and system names.
Most C programmers use all-lowercase variable names. Some names like int, while, for, and float have a special meaning to C and are considered reserved words. They cannot be used for variable names.
The following is an example of some variable names:
average            /* average of all grades */ 
pi                 /* pi to 6 decimal places */ 
number_of_students /* number students in this class */
The following are not variable names:
3rd_entry   /* Begins with a number */ 
all$done    /* Contains a "$" */ 
the end     /* Contains a space */ 
int         /* Reserved word */
Avoid variable names that are similar. For example, the following illustrates a poor choice of variable names:
total       /* total number of items in current entry */ 
totals      /* total of all entries */
A much better set of names is:
entry_total /* total number of items in current entry */ 
all_total   /* total of all entries */
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variable Declarations
Before you can use a variable in C, it must be defined in a declaration statement.
A va