The Anatomy of a C++ Program

by Bradley Jones

C++ programs consist of classes, functions, variables, and other component parts. To get a sense of how a program fits together, you must see a complete working program.

      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!

Using the Standard Namespace

You'll notice that the use of std:: in front of both cout and endl becomes rather distracting after a while. Although using the namespace designation is good form, it is tedious to type. The ANSI standard allows two solutions to this minor problem.

The first is to tell the compiler, at the beginning of the code listing, that you'll be using the standard library cout and endl, as shown on lines 5 and 6 of Listing 2.3.

Listing 2.3 Using the using Keyword

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


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!


You will note that the output is identical to the previous listing. The only difference between Listing 2.3 and Listing 2.2 is that on lines 5 and 6, additional statements inform the compiler that two objects from the standard library will be used. This is done with the keyword using. After this has been done, you no longer need to qualify the cout and endl objects.

The second way to avoid the inconvenience of writing std:: in front of cout and endl is to simply tell the compiler that your listing will be using the entire standard namespace; that is, any object not otherwise designated can be assumed to be from the standard namespace. In this case, rather than writing using std::cout;, you would simply write using namespace std;, as shown in Listing 2.4.

Listing 2.4 Using the namespace Keyword

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


Again, the output is identical to the earlier versions of this program. The advantage to writing using namespace std; is that you do not have to specifically designate the objects you're actually using (for example, cout and endl;). The disadvantage is that you run the risk of inadvertently using objects from the wrong library.

Purists prefer to write std:: in front of each instance of cout or endl. The lazy prefer to write using namespace std; and be done with it. In this book, most often the individual items being used are declared, but from time to time each of the other styles are presented just for fun.

Commenting Your Programs

When you are writing a program, your intent is always clear and self-evident to you. Funny thing, though—a month later, when you return to the program, it can be quite confusing and unclear. No one is ever certain how the confusion creeps into a program, but it nearly always does.

To fight the onset of bafflement, and to help others understand your code, you need to use comments. Comments are text that is ignored by the compiler, but that can inform the reader of what you are doing at any particular point in your program.

Types of Comments

C++ comments come in two flavors: single-line comments and multiline comments. Single-line comments are accomplished using a double slash (//) . The double slash tells the compiler to ignore everything that follows, until the end of the line.

Multiline comments are started by using a forward slash followed by an asterisk (/*). This "slash-star" comment mark tells the compiler to ignore everything that follows until it finds a "star-slash" (*/) comment mark. These marks can be on the same line or they can have one or more lines between them; however, every /* must be matched with a closing */.

Many C++ programmers use the double-slash, single-line comments most of the time and reserve multiline comments for blocking out large blocks of a program. You can include single-line comments within a block commented out by the multiline comment marks; everything, including the double-slash comments, is ignored between the multiline comment marks.

Note - The multiline comment style has been referred to as C-style because it was introduced and used in the C programming language. Single-line comments were originally a part of C++ and not a part of C; thus, they have been referred to as C++-style. The current standards for both C and C++ now include both styles of comments.

Using Comments

Some people recommend writing comments at the top of each function, explaining what the function does and what values it returns. Functions should be named so that little ambiguity exists about what they do, and confusing and obscure bits of code should be redesigned and rewritten so as to be self-evident. Comments should not be used as an excuse for obscurity in your code.

This is not to suggest that comments ought never be used, only that they should not be relied upon to clarify obscure code; instead, fix the code. In short, you should write your code well, and use comments to supplement understanding. Listing 2.5 demonstrates the use of comments, showing that they do not affect the processing of the program or its output.

Listing 2.5 Demonstrates Comments

  1: #include <iostream>
  3: int main()
  4: { 
  5:   using std::cout;
  7:   /* this is a comment
  8:   and it extends until the closing
  9:   star-slash comment mark */
 10:   cout << "Hello World!\ n";
 11:   // this comment ends at the end of the line
 12:   cout << "That comment ended!\ n";
 14:   // double-slash comments can be alone on a line
 15:   /* as can slash-star comments */
 16:   return 0;
 17: }


Hello World!
That comment ended!


The comment on lines 7–9 is completely ignored by the compiler, as are the comments on lines 11, 14, and 15. The comment on line 11 ended with the end of the line. The comments on lines 7 and 15 required a closing comment mark.

Note - A third style of comment is supported by some C++ compilers. These comments are referred to as document comments and are indicated using three forward slashes (///). The compilers that support this style of comment allow you to generate documentation about the program from these comments. Because these are not currently a part of the C++ standard, they are not covered here.

A Final Word of Caution About Comments

Comments that state the obvious are less than useful. In fact, they can be counterproductive because the code might change and the programmer might neglect to update the comment. What is obvious to one person might be obscure to another, however, so judgment is required when adding comments. The bottom line is that comments should not say what is happening, they should say why it is happening.


Although main() is a function, it is an unusual one. To be useful, a function must be called, or invoked, during the course of your program. main() is invoked by the operating system.

A program is executed line-by-line in the order it appears in your source code until a function is reached. Then the program branches off to execute the function. When the function finishes, it returns control to the line of code immediately following the call to the function.

A good analogy for this is sharpening your pencil. If you are drawing a picture and your pencil point breaks, you might stop drawing, go sharpen the pencil, and then return to what you were doing. When a program needs a service performed, it can call a function to perform the service and then pick up where it left off when the function is finished running. Listing 2.6 demonstrates this idea.

Note - Functions are covered in more detail in Lesson 6, "Organizing Code with Functions." The types that can be returned from a function are covered in more detail in Lesson 3, "Using Variables, Declaring Constants." The information provided in the current lesson is to present you with an overview because functions will be used in almost all of your C++ programs.

Listing 2.6 Demonstrating a Call to a Function

  1: #include <iostream>
  3: // function Demonstration Function
  4: // prints out a useful message
  5: void DemonstrationFunction()
  6: { 
  7:   std::cout << "In Demonstration Function\ n";
  8: } 
 10: // function main - prints out a message, then
 11: // calls DemonstrationFunction, then prints out
 12: // a second message.
 13: int main()
 14: { 
 15:   std::cout << "In main\ n" ;
 16:   DemonstrationFunction();
 17:   std::cout << "Back in main\ n";
 18:   return 0;
 19: }


In main
In Demonstration Function
Back in main


The function DemonstrationFunction() is defined on lines 6–8. When it is called, it prints a message to the console screen and then returns.

Line 13 is the beginning of the actual program. On line 15, main() prints out a message saying it is in main(). After printing the message, line 16 calls DemonstrationFunction(). This call causes the flow of the program to go to the DemonstrationFunction() function on line 5. Any commands in DemonstrationFunction() are then executed. In this case, the entire function consists of the code on line 7, which prints another message. When DemonstrationFunction() completes (line 8), the program flow returns to from where it was called. In this case, the program returns to line 17, where main() prints its final line.

Using Functions

Functions either return a value or they return void, meaning they do not return anything. A function that adds two integers might return the sum, and thus would be defined to return an integer value. A function that just prints a message has nothing to return and would be declared to return void.

Functions consist of a header and a body. The header consists, in turn, of the return type, the function name, and the parameters to that function. The parameters to a function enable values to be passed into the function. Thus, if the function were to add two numbers, the numbers would be the parameters to the function. Here's an example of a typical function header that declares a function named Sum that receives two integer values (first and second) and also returns an integer value:

int Sum( int first, int second)

A parameter is a declaration of what type of value will be passed in; the actual value passed in when the function is called is referred to as an argument. Many programmers use the terms parameters and arguments as synonyms. Others are careful about the technical distinction. The distinction between these two terms is not critical to your programming C++, so you shouldn't worry if the words get interchanged.

The body of a function consists of an opening brace, zero or more statements, and a closing brace. The statements constitute the workings of the function.

A function might return a value using a return statement. The value returned must be of the type declared in the function header. In addition, this statement causes the function to exit. If you don't put a return statement into your function, it automatically returns void (nothing) at the end of the function. If a function is supposed to return a value but does not contain a return statement, some compilers produce a warning or error message.

Listing 2.7 demonstrates a function that takes two integer parameters and returns an integer value. Don't worry about the syntax or the specifics of how to work with integer values (for example, int first) for now; that is covered in detail in Lesson 3.

Listing 2.7 FUNC.cpp Demonstrates a Simple Function

  1: #include <iostream>
  2: int Add (int first, int second)
  3: { 
  4:   std::cout << "Add() received "<< first << " and
       "<< second << Â"\ n";
  5:   return (first + second);
  6: } 
  8: int main()
  9: { 
 10:   using std::cout;
 11:   using std::cin;
 14:   cout << "I'm in main()!\ n";
 15:   int a, b, c;
 16:   cout << "Enter two numbers: ";
 17:   cin >> a;
 18:   cin >> b;
 19:   cout << "\ nCalling Add()\ n";
 20:   c=Add(a,b);
 21:   cout << "\ nBack in main().\ n";
 22:   cout << "c was set to " << c;
 23:   cout << "\ nExiting...\ n\ n";
 24:   return 0;
 25: }


I'm in main()!
Enter two numbers: 3 5

Calling Add()
In Add(), received 3 and 5

Back in main().
c was set to 8


The function Add() is defined on line 2. It takes two integer parameters and returns an integer value. The program itself begins on line 8. The program prompts the user for two numbers (line 16). The user types each number, separated by a space, and then presses the Enter key. The numbers the user enters are placed in the variables a and b on lines 17 and 18. On line 20, the main() function passes the two numbers typed in by the user as arguments to the Add() function.

Processing branches to the Add() function, which starts on line 2. The values from a and b are received as parameters first and second, respectively. These values are printed and then added. The result of adding the two numbers is returned on line 5, at which point the function returns to the function that called it—main(), in this case.

On lines 17 and 18, the cin object is used to obtain a number for the variables a and b. Throughout the rest of the program, cout is used to write to the console. Variables and other aspects of this program are explored in depth in the next lesson.

Methods Versus Functions

A function by any other name is still just a function. It is worth noting here that different programming languages and different programming methodologies might refer to functions using a different term. One of the more common words used is method. Method is simply another term for functions that are part of a class.


The difficulty in learning a complex subject, such as programming, is that so much of what you learn depends on everything else there is to learn. Today's lesson introduced the basic parts of a simple C++ program.


  1. What does #include do?
  2. This is a directive to the preprocessor that runs when you call your compiler. This specific directive causes the file in the <> named after the word #include to be read in as if it were typed in at that location in your source code.
  3. What is the difference between // comments and /* style comments?
  4. The double-slash comments (//) expire at the end of the line. Slash-star (/*) comments are in effect until a closing comment mark (*/). The double-slash comments are also referred to as single-line comments, and the slash-star comments are often referred to as multiline comments. Remember, not even the end of the function terminates a slash-star comment; you must put in the closing comment mark or you will receive a compile-time error.
  5. What differentiates a good comment from a bad comment?
  6. A good comment tells the reader why this particular code is doing whatever it is doing or explains what a section of code is about to do. A bad comment restates what a particular line of code is doing. Lines of code should be written so that they speak for themselves. A well-written line of code should tell you what it is doing without needing a comment.


The Workshop provides quiz questions to help you solidify your understanding of the material covered and exercises to provide you with experience in using what you've learned. Try to answer the quiz and exercise questions before checking the answers in Appendix D, and be certain that you understand the answers before continuing to the next lesson.


  1. What is the difference between the compiler and the preprocessor?
  2. Why is the function main() special?
  3. What are the two types of comments and how do they differ?
  4. Can comments be nested?
  5. Can comments be longer than one line?


  1. Write a program that writes I love C++ to the console.
  2. Write the smallest program that can be compiled, linked, and run.
  3. BUG BUSTERS: Enter this program and compile it. Why does it fail? How can you fix it?

    1: #include <iostream>
    2: main()
    3: { 
    4:   std::cout << Is there a bug here?";
    5: }
  4. Fix the bug in Exercise 3 and recompile, link, and run it.
  5. Modify Listing 2.7 to include a subtract function. Name this function Subtract() and use it in the same way that the Add() function was called. You should also pass the same values that were passed to the Add() function.

Copyright © 2008 Pearson Education. All rights reserved.

This article was originally published on Thursday Sep 4th 2008
Mobile Site | Full Site