MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Your first C++ program

You now know almost enough of the basics to create and compile a program. The program will use the Standard C++ iostream classes. These read from and write to files and “standard” input and output (which normally comes from and goes to the console, but may be redirected to files or devices). In this very simple program, a stream object will be used to print a message on the screen.

Using the iostreams class

To declare the functions and external data in the iostreams class, include the header file with the statement

#include <iostream>

The first program uses the concept of standard output, which means “a general-purpose place to send output.” You will see other examples using standard output in different ways, but here it will just go to the console. The iostream package automatically defines a variable (an object) called cout that accepts all data bound for standard output.

To send data to standard output, you use the operator <<. C programmers know this operator as the “bitwise left shift,” which will be described in the next chapter. Suffice it to say that a bitwise left shift has nothing to do with output. However, C++ allows operators to be overloaded. When you overload an operator, you give it a new meaning when that operator is used with an object of a particular type. With iostream objects, the operator << means “send to.” For example:

cout << "howdy!";

sends the string “howdy!” to the object called cout (which is short for “console output”).

That’s enough operator overloading to get you started. Chapter XX covers operator overloading in detail.

Namespaces

As mentioned in the previous chapter, one of the problems encountered in the C language is that you “run out of names” for functions and identifiers when your programs reach a certain size. Of course, you don’t really run out of names – however, it becomes harder to think of new ones after awhile. More importantly, when a program reaches a certain size it’s typically broken up into pieces, each of which is built and maintained by a different person or group. Since C effectively has a single arena where all the identifier and function names live, this means that all the developers must be careful not to accidentally use the same names in situations where they can conflict. This rapidly becomes tedious, time-wasting and, ultimately, expensive.

Standard C++ has a mechanism to prevent this collison: the namespace keyword. Each set of C++ definitions in a library or program is “wrapped” in a namespace, and if some other definition has an identical name, but is in a different namespace, then there is no collision.

Namespaces are a convenient and helpful tool, but their presence means you must be aware of them before you can write any programs at all. If you simply include a header file and use some functions or objects from that header, you’ll probably get strange-sounding errors when you try to compile the program, to the effect that the compiler cannot find any of the declarations for the items that you just included in the header file! After you see this message a few times you’ll become familiar with its meaning (which is: “you included the header file but all the declarations are within a namespace and you didn’t tell the compiler that you wanted to use the declarations in that namespace”).

There’s a keyword that allows you to say “I want to use the declarations and/or definitions in this namespace.” This keyword, appropriately enough, is using. All of the Standard C++ libraries are wrapped in a single namespace, which is std (for “standard”). As this book uses the standard libraries almost exclusively, you’ll see the following using directive in almost every program:

using namespace std;

This means that you want to expose all the elements from the namespace called std. After this statement, you don’t have to worry that your particular library component is inside a namespace, since the using directive makes that namespace available throughout the file where the using directive was written.

Exposing all the elements from a namespace after someone has gone to the trouble to hide them may seem a bit counterproductive, and in fact you should be careful about thoughtlessly doing this (as you’ll learn later in the book). However, the using directive only exposes those names for the current file, so it is not quite so drastic as it first sounds (but think twice about doing it in a header file – that is reckless).

There’s a relationship between namespaces and the way header files are included. Before the current header file inclusion style of <iostream> (that is, no trailing ‘ .h’) was standardized, the typical way to include a header file was with the ‘ .h’, such as <iostream.h>. At that time, namespaces were not part of the language, either. So to provide backwards compatibility with existing code, if you say

#include <iostream.h>

It means

#include <iostream>
using namespace std; 

However, in this book the standard include format will be used (without the ‘ .h’) and so the using directive must be explicit.

For now, that’s all you need to know about namespaces, but in Chapter XX the subject is covered much more thoroughly.

Fundamentals of program structure

A C or C++ program is a collection of variables, function definitions and function calls. When the program starts, it executes initialization code and calls a special function, “ main( ).” You put the primary code for the program here.

As mentioned earlier, a function definition consists of a return type (which must be specified in C++), a function name, an argument list in parentheses, and the function code contained in braces. Here is a sample function definition:

int function() {
  // Function code here (this is a comment)
}

The above function has an empty argument list, and a body that contains only a comment.

There can be many sets of braces within a function definition, but there must always be at least one set surrounding the function body. Since main( ) is a function, it must follow these rules. In C++, main( ) always has return type of int.

C and C++ are free form languages. With few exceptions, the compiler ignores newlines and white space, so it must have some way to determine the end of a statement. Statements are delimited by semicolons.

C comments start with /* and end with */. They can include newlines. C++ uses C-style comments and has an additional type of comment: //. The // starts a comment that terminates with a newline. It is more convenient than /* */ for one-line comments, and is used extensively in this book.

"Hello, world!"

And now, finally, the first program:

//: C02:Hello.cpp
// Saying Hello with C++
#include <iostream> // Stream declarations
using namespace std;

int main() {
  cout << "Hello, World! I am " << 8 << " Today!" << endl;
} ///:~ 

The cout object is handed a series of arguments via the ‘ <<’ operators. It prints out these arguments in left-to-right order. The special iostream function endl outputs the line and a newline. With iostreams, you can string together a series of arguments like this, which makes the class easy to use.

In C, text inside double quotes is traditionally called a “string.” However, the Standard C++ library has a powerful class called string for manipulating text, and so I shall use the more precise term character array for text inside double quotes.

The compiler creates storage for character arrays and stores the ASCII equivalent for each character in this storage. The compiler automatically terminates this array of characters with an extra piece of storage containing the value 0, to indicate the end of the character array.

Inside a character array, you can insert special characters by using escape sequences. These consist of a backslash ( \) followed by a special code. For example \n means newline. Your compiler manual or local C guide gives a complete set of escape sequences; others include \t (tab), \\ (backslash) and \b (backspace).

Notice that the entire statement terminates with a semicolon.

Character array arguments and constant numbers are mixed together in the above cout statement. Because the operator << is overloaded with a variety of meanings when used with cout, you can send cout a variety of different arguments, and it will “figure out what to do with the message.”

Throughout this book you’ll notice that the first line of each file will be a comment that starts with the characters that start a comment, followed by a colon. This is a technique I use to allow easy extraction of information from code files (the program to do this is in the last chapter of the book). The first line also has the name and location of the file, so it can be referred to in text and in other files, and so you can easily locate it in the source code for this book (which is freely downloadable from http://www.BruceEckel.com, where you’ll find instructions as to how to unpack it).

Running the compiler

After downloading and unpacking the book’s source code, find the program in the subdirectory CO2. Invoke the compiler with Hello.cpp as the argument. For simple, one-file programs like this one, most compilers will take you all the way through the process. For example, to use the Gnu C++ compiler (which is freely available on the Internet), you say:

g++ Hello.cpp

Other compilers will have a similar syntax; consult your compiler’s documenation for details.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru