BUY THIS BOOK
Add to Cart

Print Book $39.95


Add to Cart

Print+PDF $51.94

Add to Cart

PDF $31.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £28.50

What is this?

Looking to Reprint or License this content?


Practical C++ Programming
Practical C++ Programming, Second Edition By Steve Oualline
December 2002
Pages: 574

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: What Is C++?
Profanity is the one language that all programmers understand.
—Anonymous
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. However, they can't do anything until someone tells them what to do. That's where C++ comes in. C++ is a high-level 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 1980, it has been used for a wide variety of programs including firmware for microcontrollers, operating systems, applications, and graphics programming. C++ is the programming language of choice for a tremendous number of applications. There is a tremendous demand for people who can tell computers what to do, and C++ lets you do so quickly and efficiently.
In 1970 two programmers, Brian Kernighan and Dennis Ritchie, created a new language called C. (The name came about because C was preceded by the old programming language they were using called 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 had one major problem, however. It was a procedure-oriented language. This meant that in designing a typical C program, the programmer would start by describing the data and then write procedures to manipulate that data.
Programmers eventually discovered that it made a program clearer and easier to understand if they were able to take a bunch of data and group it together with the operations that worked on that data. Such a grouping is called an object or class. Designing programs by designing classes is known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Brief History of C++
In 1970 two programmers, Brian Kernighan and Dennis Ritchie, created a new language called C. (The name came about because C was preceded by the old programming language they were using called 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 had one major problem, however. It was a procedure-oriented language. This meant that in designing a typical C program, the programmer would start by describing the data and then write procedures to manipulate that data.
Programmers eventually discovered that it made a program clearer and easier to understand if they were able to take a bunch of data and group it together with the operations that worked on that data. Such a grouping is called an object or class. Designing programs by designing classes is known as object-oriented design (OOD).
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, the most important of which was classes. This language was improved, augmented, and finally became C++.
C++ owes its success to the fact that it allows the programmer to organize and process information more effectively than most other languages. Also, it builds on the work already done with the C language. In fact, most C programs can be transformed into C++ programs with little trouble. These programs usually don't use all the new features of C++, but they do work. In this way, C++ allows programmers to build on an existing base of C 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!
C++ Organization
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 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 idea is for the programmer to impose his or her own organization on the computer and 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 or she is working with. For example:
int total;	    // Total number accounts 
tells C++ that you want to use a section of the computer's memory to store an integer named total. You can let the compiler decide what particular bytes of memory to use; that's a minor bookkeeping detail you don't need to worry about.
The 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. Again, C++ will handle the details, imposing that organization on the computer's memory.
int balance[100];   // Balance (in cents) for all 100 accounts
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 you organize these four attributes 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 	
};
However, data is only one part of a program; you also need instructions. As far as the computer is concerned, it knows nothing about the layout of the instructions. It knows only what it's doing for the current instruction and where to get the next instruction.
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++
The only way to learn how to program 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, and you should try to do as many of them as possible. When doing the exercises, keep good programming style in mind. Always comment your programs, even if you're doing the exercises only for yourself. Commenting helps you organize your thoughts, and commenting your own programs is good practice for 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 you when you write it can often be confusing and cryptic when you revisit it a week later. Writing comments also helps you organize your ideas. (If you can write out an idea in English, you are halfway to writing it in C++.)
Finally, programs tend to be around far longer than expected. I once wrote a highly system-dependent program that was designed to work only on the computer at Caltech. As I was the only one who would ever use the program, it would print the following message if I got the command line wrong:
?LSTUIT User is a twit
A few years later I was a student at Syracuse University. The chief secretary at the School of Computer Science needed a program similar to my Caltech listing program, so I adapted my program for her use. Unfortunately, I had forgotten about my funny little 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 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 might not be here today.
Sprinkled throughout are not only examples of working programs (to show you how to do things), but also examples of broken programs where we ask you to go through the program and figure out what's wrong. Often the problem is very subtle, such as a misplaced semicolon or use of
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: The 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
Computers are very powerful tools that can store, organize, and process a tremendous amount of information. However, they can't do anything until someone gives them detailed instructions.
Communicating with computers is not easy. They require instructions that are exact and detailed. Wouldn't life be easier if we could write programs in English? Then we could tell the computer, "Add up all my checks and deposits, and tell me the total," and the machine would balance our checkbooks.
But English is a lousy language when you must write 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 include instructions for every contingency. If we worked really hard, we could write precise English instructions, right?
As it turns out, 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 also has made the documents 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 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 a helmet. The man suggested the police officer take a closer look at the law.
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 can be used, it must undergo several transformations.
Programs start out as an idea in a programmer's head. She writes down her thoughts in a file, called a source file or source code, using a text editor. 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, you'll see how these various forms of the program work together to produce the final program.
Figure 2-2 shows the steps that must be taken to transform a program written in a high-level language into an executable program.
Figure 2-2: 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, which 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 you can actually start creating your own programs, you need to know how to use the basic programming tools. This section will take you step by step through the process of entering, compiling, and running a simple program.
This section describes how to use two different types of compilers. The first type is the standalone or command-line compiler. This type of compiler is operated from the command line. You type a command, and the compiler turns your source code into an executable program. The other type of compiler is contained in an IDE.
Most Unix systems use command-line compilers. A few IDE-type compilers are available for Unix, but they are rare. On the other hand, almost all the compilers used with Microsoft Windows are part of an IDE. For command-line die-hards, these IDEs contain command-line compilers as well.
In this section you'll go through the step-by-step process needed to create a program using a command-line compiler. The program you're going to create will display the message "Hello World" on the screen. Instruction is given for using a generic Unix compiler, the Free Software Foundation's g++ compiler, Borland C++, and Microsoft Visual C++.
However, if you are using a Borland or Microsoft compiler, you might want to skip ahead to Section 2.2.2.
Note that, because compilers are continually being improved, the information in this section may not be accurate by the time you read it. As new compilers come out, we'll update this section and post the update on the O'Reilly web site at http://www.oreilly.com/catalog/cplus2.

Section 2.2.1.1: Step 1: Create a place for your program

It is easier to manage things if you create a separate directory for each program you are working on. In this case you'll create a directory called hello to hold your hello program.
In Unix, type:
% mkdir hello
% cd hello
In MS-DOS, type:
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 Unix
Most Unix systems have an online documentation system called the "man pages." These can be accessed using the man command. (Unix uses man as an abbreviation for "manual.") To get information about a particular subject, use the command:
man subject 
            
For example, to find out about the classes defined in the iostream package, you would type:
man iostream 
The command also has a keyword search mode:
man -k keyword
            
To determine the name of every man page 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 IDE
IDEs such as 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!
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. It may seem backward to discuss style before you know how to program, 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 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 work. 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.2 million. The average system age has gone from 4.75 to 9.4 years.
Most software is built on existing software. I recently completed coding for 12 new programs. Only one of these was created from scratch; the other 11 are adaptations of existing programs.
Programmers believe that the purpose of a program is only to present the computer with a compact set of instructions. This 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!
Comments
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.
Example 2-1 contains a glaring error. It is an error that many programmers still make and one that causes more trouble than any other problem. The program contains no comments .
A working but uncommented program is a time bomb waiting to explode. Sooner or later someone will have to modify or upgrade the program, and the lack of comments will make the job ten times more difficult. A well-commented, simple program is a work of art. Learning how to comment is as important as learning how to code properly.
C++ has two flavors of comments. The first type starts with /* and ends with */. This type of comment can span multiple lines as shown:
/* This is a single-line comment. */
/* 
 * This is a multiline comment.
 */
The other form of comment begins with // and goes to the end of the line:
// This is another form of comment.
// The // must begin each line that is to be a comment.
The advantage of the /* */ comment style is that you can easily span multiple lines, whereas with the // style you have to keep putting the // on each line. The disadvantage of /* */ is that forgetting a */ can really screw up your code. (Remember this because it's the answer to one of the questions later in the book.)
Which flavor should you use? Whichever one makes your program as clear and as easy to read as possible. Mostly, it's a matter of taste. In this book we use the /* */ style comments for big, multiline comments, and the // style is reserved for comments that take up only a single line.
Whatever comment style you decide to use, you must comment your programs. Example 3-1 shows how the "hello world" program looks after comments are added.
Example 3-1. hello2/hello2.cpp
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
C++ Code
The actual code for your program consists of two parts: variables and executable instructions. Variables are used to hold the data used by your program. Executable instructions tell the computer what to do with the data. C++ classes are a combination of data and the instructions that work on the data. They provide a convenient way of packaging both instructions and data.
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 any length and should be chosen so their meaning is clear. (Actually, a length limit does exist, but it is so large that you probably will never encounter it.) Every variable in C++ must be declared. (Variable declarations are discussed in Chapter 9.) The following declaration tells C++ that you are going to use three integer (int) variables named 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 are dealing with an accounting program, but we could still use some more information. For example, is the balance_owed in dollars or cents? It would be much better if we added a comment after each declaration explaining what we are doing.
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. Since the definition of each variable is in a known place, it's easy to look up the meaning of a name. (Programming tools, such as editors, cross-referencers, and
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Naming Style
Names can contain both uppercase and lowercase letters. In this book we use all lowercase names for variables (e.g., source_ptr, current_index). All uppercase is reserved for constants (e.g., MAX_ITEMS, SCREEN_WIDTH). This convention is the classic convention followed by most C and C++ programs.
Many newer programs use mixed-case names (e.g., RecordsInFile). Sometimes they use the capitalization of the first letter to indicate information about the variable. For example, recordsInFile might be used to denote a local variable while RecordsInFile would denote a global variable. (See Chapter 9 for information about local and global variables.) You should be careful when making up rules for your variables because the more complex the rules, the more likely someone will violate them or get confused.
One additional note on variable names: please use whole words. The problem with abbreviations is that there are too many different ways of abbreviating the same word. This is especially true when programmers think that to abbreviate a word, you write down the word and then cross out random letters. I've seen "Ground Point" named gp, ground_pt, gnd_pt, g_pnt, and many others. On the other hand, there's only one full spelling: ground_point.
Also, I work for a company which has people from 62 different countries working together to produce code. The non-English speakers have real difficulty looking up the more unusual abbreviations. Words in the dictionary make things much easier to understand for people who have to deal with the twin complexities of English and C++.
Which naming convention you use is up to you. It is more a matter of religion than of style. However, using a consistent naming style is extremely important. In this book we have chosen the first style—lowercase variable names and uppercase constants—and we use it throughout the book. (Note that this convention is growing less common as old-style #define constants are being replaced with new-style
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, and goto -less programming. Each of these styles has its own following or cult. I use the term "religion" because people are taught to follow the rules 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 are the result of 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 it 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
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 Example 3-1 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. The statement inside the if (break) is at the innermost level.
There are two styles of indentation, and a vast religious war is being waged in the programming community as to which is better. The first is the short form:
while (! done) { 
    std::cout << "Processing\n"; 
    next_entry(  ); 
} 

if (total <= 0) { 
    std::cout << "You owe nothing\n"; 
    total = 0; 
} else { 
    std::cout << "You owe " << total << " dollars\n"; 
    all_totals = all_totals + total; 
} 
In this case, most of the curly braces are put on the same line as the statements. The other style puts the curly braces on lines by themselves:
while (! done)  
{ 
    std::cout << "Processing\n"; 
    next_entry(  ); 
} 

if (total <= 0)  
{ 
   std::cout << "You owe nothing\n"; 
   total = 0; 
} 
else  
{ 
   std::cout << "You owe " << total << " dollars\n"; 
   all_totals = all_totals + total; 
} 
Both formats are commonly used. You should use the format you feel most comfortable with. This book uses the short form. (It saves paper.)
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 most readable code. You can choose any indent size as long as you are consistent.
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, organized into sections and paragraphs. Procedures form a natural section boundary. You should organize your code into paragraphs, beginning a paragraph with a topic sentence comment and separating it 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. Here are some general rules of thumb:
  • A single function should not be longer than one or two pages. (See Chapter 9.) If it gets longer, it can probably be split into two simpler functions. This rule comes about because the human mind can hold only so much in short-term memory: three pages is about the maximum for a single sitting.
  • Avoid complex logic such as multiple nested ifs. The more complex your code, the more indentation levels you will need. About the time you start running into the right margin, you should think about splitting your code into multiple procedures and thus decreasing the level of complexity.
  • Did you ever read a sentence, like this one, where 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 an equation or formula looks like it is going to be longer than one or two lines, you probably should split it into two shorter equations.
  • Split large single code files into multiple smaller ones. (See Chapter 23 for more information about programming with multiple files.) In general I like to keep my files smaller than 1,500 lines. That way they aren't too difficult to edit and print.
  • When using classes (see Chapter 13), put one class per module.
  • Finally, the most important rule: make your program as simple and easy to understand as possible, even if it means breaking some of the rules. The goal is clarity, and the rules given in this chapter are designed to help you accomplish that goal. If the rules get in the way, get rid of them. I have seen a program with a single statement that spanned more than 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!
Consistency and Organization
Good style is only one element in creating a high-quality program. Consistency is also a factor. This book is organized with the table of contents at the front and the index at the back. Almost every book printed has a similar organization. This consistency makes it easy to look up a word in the index or find a chapter title in the table of contents.
Unfortunately, the programming community has developed a variety of coding styles. Each has its own advantages and disadvantages. The trick to efficient programming in a group is to pick one style and use it consistently. That way you can avoid the problems and confusion that arise when programs written in different styles are combined.
Good style is nice, but consistency is better.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Further Reading
In this chapter we have touched only the basics of style. Later chapters expand on this base, adding new stylistic elements as you learn new elements of the language.
For a more complete discussion of style, the online book C Elements of Style is available from http://www.oualline.com.
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: they describe your program to any maintenance programmer who has to fix it, and they help you remember what you did.
Class discussion 1: Create a style sheet for class assignments. Discuss what comments should go into the programs and why.
Class discussion 2: Analyze the style of an existing program. Is the program written in a manner that is clear and easy to understand? What can be done to improve the style of the 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!
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.
—Anonymous
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 also need two things: data (variables) and instructions (code). 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 it 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++ you must declare all variables before you can use them. You must name each one of your "bricks" and tell C++ what type of "brick" to use.
After the variables are defined, you 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, and functions can be combined to form a program.
An apprentice builder does not start out building the Empire State Building. He starts on a one-room house. In this chapter you 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
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); 
} 
The heading comments tell the programmer all about the program. The 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. Any 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 that the program exited normally (status=0). A nonzero status indicates an error—the bigger the return value, the more severe the error. Typically 1 is used for most simple errors, such as a missing file or bad command-line syntax.
Now let's take a look at the "Hello World" program (Example 2-1).
At the beginning of the program is a comment box enclosed in /* and */. Next we have the line:
#include <iostream> 
This tells C++ that we want to use the standard input/output system. (The proper name for this is the I/O streams module.) This is a type of data declaration.
The main routine contains the instruction:
    std::cout << "Hello World\n"; 
This instruction is an executable statement telling C++ to write the message "Hello World" on the screen. The special character sequence \n tells C++ to write out a newline character. 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, the end of a line does not end a statement. The sentences in this book can span several lines—the end of a line is treated as a space separating 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. C++ has the five simple operators listed in Table 4-1.
Table 4-1: Simple operators
Operator
Meaning
*
Multiply
/
Divide
+
Add
-
Subtract
%
Modulus (remainder after division)
Multiply (*), divide (/), and modulus (%) have precedence over addition (+) and subtraction (-). Parentheses may be used to group terms. Thus, the following expression yields 12:
(1 + 2) * 4 
The next expression yields 9:
1 + 2 * 4 
The program in Example 4-1 computes the value of the expression
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The std::cout Output Object
The standard object std::cout is used to output data to the console. We'll learn what a object is later in Chapter 13, but for now all we have to know is that the operator << tells C++ what to output.
So the statement:
std::cout << "Hello World\n";
tells C++ to take the string "Hello World\n" and write it to the console. Multiple << operators may be used together. For example, both the following lines output the same message:
std::cout << "Hello World\n";
std::cout << "Hello " << "World\n";
Expressions can also be output this way, such as:
std::cout << "Half of " << 64 << " is " << (64 / 2) << "\n";
When this is executed, it will write:
Half of 64 is 32
on the console. Note that we had to put a space after the "of" in "Half of". There also is a space on either side of the "is" string. These spaces are needed in the output to separate the numbers from the text. Suppose we didn't put the spaces in, and the code looked like this:
// Problem code
std::cout << "Half of" << 64 << "is" << (64 / 2) << "\n";
At first glance this code looks perfectly normal. There are spaces around each of the numbers. But these spaces are not inside any string, so they will not be output. The result of this code is:
Half of64is32
Omitting needed spaces is a common first-time programming mistake. Remember, only the text inside the quotation marks will be 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!
Variables and Storage
C++ allows you to store values in variables. Each variable is identified by a variable name.
Additionally, 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 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. To avoid confusion, it is better to use different names for variables and not depend on case differences.
Some C++ programmers use all lowercase variable names. Some names, such as int, while, for, and float , have a special meaning to C++ and are considered reserved words , also called keywords. 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 of 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
This is a much better set of names:
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 variable cannot be used unless it is declared.
A variable declaration serves three purposes:
  • It defines the name of the variable.
  • It defines the type of the variable (integer, real, character, etc.).
  • It gives the programmer a description of the variable.
The declaration of a variable answer can be:
int answer;     // the result of our expression
The keyword int tells C++ that this variable contains an integer value. (Integers are defined below.) The variable name is answer. The semicolon is used to indicate the statement end, and the comment is used to define this variable for the programmer.
The general form of a variable declaration is:
               type  
               name;   // comment 
            
Type is one of the C++ variable types (int , float, etc.) Name is any valid variable name. The comment explains what the variable is and what it will be used for. Variable declarations come just before the main( ) line at the top of a program. (In Chapter 9 you will see how local variables may be declared elsewhere.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Integers
One variable type is integer. Integers (also known as whole numbers) have no fractional part or decimal point. Numbers such as 1, 87, and -222 are integers. The number 8.3 is not an integer because it contains a decimal point. The general form of an integer declaration is:
    int  name;   // comment
            
A calculator with an eight-digit display can only handle numbers between 99,999,999 and -99,999,999. If you try to add 1 to 99,999,999, you will get an overflow error. Computers have similar limits. The limits on integers are implementation- dependent, meaning they change from computer to computer.
Calculators use decimal digits (0-9). Computers use binary digits (0-1) called bits. Eight bits make a byte. The number of bits used to hold an integer varies from machine to machine. Numbers are converted from binary to decimal for printing.
On most machines integers are 32 bits (4 bytes), providing a range of 2,147,483,647 (231- 1) to -2,147,483,648 (-231). Some systems now use newer processors such as the Intel Itanium, which have 64-bit integers, giving you a range of 9223372036854775807 (263-1) to -9223372036854775807 (-263) If you are programming using an older MS-DOS compiler, only 16 bits (2 bytes) are used, so the range is 32,767 (215-1) to -32,768 (-215).
Question 4-1: The following will work on a Unix machine but will fail on an old MS-DOS system.
int zip;      // zip code for current address

......... 

zip = 92126; 
Why does this fail? What will be the result when this program is run on an MS-DOS 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!
Assignment Statements
Variables are given a value through the use of assignment statements. Before a variable can be used, it must be declared. For example:
int answer;    // Result of a simple computation
The variable may then be used in an assignment statement, such as:
answer = (1 + 2) * 4; 
The variable answer on the left side of the equal sign (=) is assigned the value of the expression (1 + 2) * 4 on the right side. The semicolon ends the statement.
When you declare a variable, C++ allocates storage for the variable and puts an unknown value inside it. You can think of the declaration as creating a box to hold the data. When it starts out, it is a mystery box containing an unknown quantity. This is illustrated in Figure 4-1A. The assignment statement computes the value of the expression and drops that value into the box, as shown in Figure 4-1B.
Figure 4-1: Declaration and assignment statements
The general form of the assignment statement is:
               variable = expression; 
The equal sign (=) is used for assignment, not equality.
In Example 4-2, the variable term is used to store an integer value that is used in two later expressions. Variables, like expressions, can be output using the output operator <<, so we use this operator to check the results.
Example 4-2. tterm/tterm.cpp
#include <iostream>

int term;       // term used in two expressions
int main(  )
{

    term = 3 * 5;
    std::cout << "Twice " << term << " is " << 2*term << "\n";
    std::cout << "Three times " << term << " is " << 3*term << "\n";
    return (0);
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Floating-Point Numbers
Real numbers are numbers that have a fractional part. Because of the way they are stored internally, real numbers are also known as floating-point numbers. The numbers 5.5, 8.3, and -12.6 are all floating-point numbers. C++ uses the decimal point to distinguish between floating-point numbers and integers, so a number such as 5.0 is a floating-point number while 5 is an integer. Floating-point numbers must contain a decimal point. Numbers such as 3.14159, 0.5, 1.0, and 8.88 are floating-point numbers.
Although it is possible to omit digits before the decimal point and specify a number as .5 instead of 0.5, the extra 0 makes it clear that you are using a floating-point number. A similar rule applies to 12. versus 12.0. Floating-point zero should be written as 0.0.
Additionally, a floating-point number may include an exponent specification of the form e±exp. For example, 1.2e34 is shorthand for 1.2×1034.
The form of a floating-point declaration is:
float variable;   // comment
            
Again, there is a limit on the range of floating-point numbers the computer can handle. The range varies widely from computer to computer. Floating-point accuracy is discussed further in Chapter 19.
Floating-point numbers may be output using std::cout. For example:
std::cout << "The answer is " << (1.0 / 3.0) << "\n";
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Floating-Point Divide Versus Integer Divide
Content preview·