The Anatomy of a C++ Program

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

      Excerpt from Sams Teach Yourself C++ in One Hour a Day, 6th Edition. By Jesse Liberty, Siddhartha Rao, and Bradley L. Jones
Published by Sams Publishing
ISBN-10: 0672329417
ISBN-13: 9780672329418

This excerpt is used with permission of Pearson from the book Sams Teach Yourself C++ in One Hour a Day, 6th Edition from Sams by Jesse Liberty, Siddhartha Rao, and Bradley L. Jones.

Lesson 2: The Anatomy of a C++ Program

C++ programs consist of classes, functions, variables, and other component parts. Most of this book is devoted to explaining these parts in depth, but to get a sense of how a program fits together, you must see a complete working program.

In this lesson, you will learn

  • The parts of a C++ program
  • How the parts work together
  • What a function is and what it does

A Simple Program

Even the simple program HELLO.cpp from Lesson 1, “Getting Started,” had many interesting parts. This section reviews this program in more detail. Listing 2.1 reproduces the original version of HELLO.cpp for your convenience.

Listing 2.1 HELLO.cpp Demonstrates the Parts of a C++ Program

 1: #include <iostream>
 3: int main()
 4: {
 5:   std::cout << "Hello World!\ n";
 6:   return 0;
 7: }


Hello World!


On the first line, the file iostream is included into the current file. Here’s how that works: The first character is the # symbol, which is a signal to a program called the preprocessor. Each time you start your compiler, the preprocessor is run first. The preprocessor reads through your source code, looking for lines that begin with the pound symbol (#) and acts on those lines before the compiler runs. The preprocessor is discussed in further detail in Lesson 15, “An Introduction to Macros and Templates,” and in Lesson 29, “Tapping Further into the Preprocessor.”

The command #include is a preprocessor instruction that says, “What follows is a filename. Find that file, read it, and place it right here.” The angle brackets around the filename tell the preprocessor to look in all the usual places for this file. If your compiler is set up correctly, the angle brackets cause the preprocessor to look for the file iostream in the directory that holds all the include files for your compiler. The file iostream (input-output-stream) is used by cout, which assists with writing to the console. The effect of line 1 is to include the file iostream into this program as if you had typed it in yourself.

Note – The preprocessor runs before your compiler each time the compiler is invoked. The preprocessor translates any line that begins with a pound symbol (#) into a special command, getting your code file ready for the compiler.

Not all compilers are consistent in their support for #includes that omit the file extension. If you get error messages, you might need to change the include search path for your compiler or add the extension to the #include.

The actual program starts with the function named main(). Every C++ program has a main() function. A function is a block of code that performs one or more actions. Usually, functions are invoked or called by other functions, but main() is special. When your program starts, main() is called automatically.

main(), like all functions, must state what kind of value it returns. The return value type for main() in HELLO.cpp is int, which means that this function returns an integer to the operating system when it completes. In this case, it returns the integer value 0. A value may be returned to the operating system to indicate success or failure, or using a failure code to describe a cause of failure. This may be of importance in situations where an application is launched by another. The application that launches can use this “exit code” to make decisions pertaining to success or failure in the execution of the application that was launched.

Caution – Some compilers let you declare main() to return void. This is no longer legal C++, and you should not get into bad habits. Have main() return int, and simply return 0 as the last line in main().

Note – Some operating systems enable you to test the value returned by a program. The informal convention is to return 0 to indicate that the program ended normally.

All functions begin with an opening brace ({) and end with a closing brace (}). Everything between the opening and closing braces is considered a part of the function.

The meat and potatoes of this program is in the usage of std::cout. The object cout is used to print a message to the screen. You’ll learn about objects in general in Lesson 10, “Classes and Objects,” and cout and cin in detail in Lesson 27, “Working with Streams.” These two objects, cin and cout, are used in C++ to handle input (for example, from the keyboard) and output (for example, to the console), respectively.

cout is an object provided by the standard library. A library is a collection of classes. The standard library is the standard collection that comes with every ANSI-compliant compiler.

You designate to the compiler that the cout object you want to use is part of the standard library by using the namespace specifier std. Because you might have objects with the same name from more than one vendor, C++ divides the world into namespaces. A namespace is a way to say, “When I say cout, I mean the cout that is part of the standard namespace, not some other namespace.” You say that to the compiler by putting the characters std followed by two colons before the cout.

Here’s how cout is used: Type the word cout, followed by the output redirection operator (<<). Whatever follows the output redirection operator is written to the console. If you want a string of characters written, be certain to enclose them in double quotes ("), as visible in Listing 2.1.

Note – You should note that the redirection operator is two greater-than signs with no spaces between them.

A text string is a series of printable characters. The final two characters, \ n, tell cout to put a new line after the words Hello World!

The main() function ends with the closing brace (} ).

A Brief Look at cout

In Lesson 27, you will see how to use cout to print data to the screen. For now, you can use cout without fully understanding how it works. To print a value to the screen, write the word cout, followed by the insertion operator (<<), which you create by typing the less-than character (<) twice. Even though this is two characters, C++ treats it as one.

Follow the insertion character with your data. Listing 2.2 illustrates how this is used. Type in the example exactly as written, except substitute your own name where you see Jesse Liberty (unless your name is Jesse Liberty).

Listing 2.2 Using cout

  1: // Listing 2.2 using std::cout
  2: #include <iostream>
  3: int main()
  4: {
  5:   std::cout << "Hello there.\ n";
  6:   std::cout << "Here is 5: " << 5 << "\ n";
  7:   std::cout << "The manipulator std::endl ";
  8:   std::cout << "writes a new line to the screen.";
  9:   std::cout << std::endl;
 10:   std::cout << "Here is a very big number:\ t" << 70000;
 11:   std::cout << std::endl;
 12:   std::cout << "Here is the sum of 8 and 5:\ t";
 13:   std::cout << 8+5 << std::endl;
 14:   std::cout << "Here's a fraction:\ t\ t";
 15:   std::cout << (float) 5/8 << std::endl;
 16:   std::cout << "And a very very big number:\ t";
 17:   std::cout << (double) 7000 * 7000 << std::endl;
 18:   std::cout << "Don't forget to replace Jesse Liberty ";
 19:   std::cout << "with your name...\ n";
 20:   std::cout << "Jesse Liberty is a C++ programmer!\ n";
 21:   return 0;
 22: }


Hello there.
Here is 5: 5
The manipulator endl writes a new line to the screen.
Here is a very big number:   70000
Here is the sum of 8 and 5:   13
Here's a fraction:       0.625
And a very very big number:   4.9e+007
Don't forget to replace Jesse Liberty with your name...
Jesse Liberty is a C++ programmer!

Caution – Some compilers have a bug that requires that you put parentheses around the addition before passing it to cout. Thus, line 13 would change to

cout << (8+5) << std::endl;


The statement #include <iostream> causes the iostream file to be added to your source code. This is required if you use cout and its related functions.

The program starts with the the simplest use of cout by printing a string; that is, a series of characters. The symbol \ n is a special formatting character. It tells cout to print a newline character to the screen; it is pronounced “slash-n” or “new line.”

Three values are passed to cout in this line:

  std::cout << "Here is 5: " << 5 << "\ n";

In here, each value is separated by the insertion operator (<<). The first value is the string "Here is 5: ". Note the space after the colon. The space is part of the string. Next, the value 5 is passed to the insertion operator and then the newline character (always in double quotes or single quotes) is passed. This causes the line

Here is 5: 5

to be printed to the console. Because no newline character is present after the first string, the next value is printed immediately afterward. This is called concatenating the two values.

Note the usage of the manipulator std::endl. The purpose of endl is to write a new line to the console, thus presenting an alternative to ‘\ n’. Note that endl is also provided by the standard library; thus, std:: is added in front of it just as std:: was added for cout.

Note – endl stands for end line and is end-ell rather than end-one. It is commonly pronounced “end-ell.”

The use of endl is preferable to the use of \ n because endl is adapted to the operating system in use, whereas \ n might not be the complete newline character required on a particular operating system or platform.

The formatting character \ t inserts a tab character. Other lines in the sample demonstrate how cout can display integers, decimal equivalents, and so on. The terms (float) and (double) tell cout that the number is to be displayed as a floating-point value. All this will be explained in Lesson 3, “Using Variables, Declaring Constants,” when data types are discussed.

You should have substituted your name for Jesse Liberty. If you do this, the output should confirm that you are indeed a C++ programmer. It must be true, because the computer said so!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read