Day 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.

Today, 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 Day 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>
2:
3:  int main()
4:  {
5:        std::cout << "Hello World! ";
6:        return 0;
7:  }

Image


Hello World!

Image

On line 1, 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 detail on Day 21, “What’s Next.”

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.

Note

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.

Line 3 begins the actual program with a 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, as shown on line 6. Returning a value to the operating system is a relatively unimportant and little used feature, but the C++ standard does require that main() be declared as shown.

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 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 (}). The braces for the main() function are on lines 4 and 7. Everything between the opening and closing braces is considered a part of the function.

The meat and potatoes of this program is on line 5.

The object cout is used to print a message to the screen. You’ll learn about objects in general on Day 6, “Understanding Object-Oriented Programming,” and cout and its related object cin in detail on Day 17, “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. You’ll learn more about namespaces in coming days.

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 shown on line 5.

Note

You should note that the redirection operator is two “less-than” signs with no spaces between them.

A text string is a series of printable characters.

The final two characters, , tell cout to put a new line after the words Hello World! This special code is explained in detail when cout is discussed on Day 18, “Creating and Using Namespaces.”

The main() function ends on line 7 with the closing brace.

A Brief Look at cout

On Day 17, 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. ";
  6:        std::cout << "Here is 5: " << 5 << " ";
  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: " << 70000;
11:       std::cout << std::endl;
12:       std::cout << "Here is the sum of 8 and 5: ";
13:       std::cout << 8+5 << std::endl;
14:       std::cout << "Here’s a fraction: ";
15:       std::cout << (float) 5/8 << std::endl;
16:       std::cout << "And a very very big number: ";
17:       std::cout << (double) 7000 * 7000 << std::endl;
18:       std::cout << "Don’t forget to replace Jesse Liberty ";
19:       std::cout << "with your name... ";
20:       std::cout << "Jesse Liberty is a C++ programmer! ";
21:       return 0;
22:  }

Image


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

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

Image

On line 2, 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.

On line 5 is the simplest use of cout, printing a string or series of characters. The symbol 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 on line 6, and 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.

On line 7, an informative message is printed, and then the manipulator std::endl is used. The purpose of endl is to write a new line to the console. (Other uses for endl are discussed on Day 16, “Advanced Inheritance.”) 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.”

Use of endl is preferable to the use of ‘ ’, because endl is adapted to the operating system in use, whereas ‘ ’ might not be the complete newline character required on a particular OS or platform.

On line 10, a new formatting character, , is introduced. This inserts a tab character and is used on lines 10 to 16 to line up the output. Line 10 shows that not only integers, but long integers as well, can be printed. Lines 13 and 14 demonstrate that cout will do simple addition. The value of 8+5 is passed to cout on line 14, but the value of 13 is printed.

On line 15, the value 5/8 is inserted into cout. The term (float) tells cout that you want this value evaluated as a decimal equivalent, and so a fraction is printed. On line 17, the value 7000 * 7000 is given to cout, and the term (double) is used to tell cout that this is a floating-point value. All this will be explained on Day 3, “Working with Variables and Constants,” when data types are discussed.

On lines 18 and 20, 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;
  6:        using std::endl;
  7:  
  8:        cout << "Hello there. ";
  9:        cout << "Here is 5: " << 5 << " ";
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: " << 70000;
14:       cout <<  endl;
15:       cout << "Here is the sum of 8 and 5: ";
16:       cout << 8+5 << endl;
17:       cout << "Here’s a fraction: ";
18:       cout << (float) 5/8 << endl;
19:       cout << "And a very very big number: ";
20:       cout << (double) 7000 * 7000 << endl;
21:       cout << "Don’t forget to replace Jesse Liberty ";
22:       cout << "with your name... ";
23:       cout << "Jesse Liberty is a C++ programmer! ";
24:       return 0;
25:  }

Image

Image

Image

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;
  6:   
  7:         cout << "Hello there. ";
  8:         cout << "Here is 5: " << 5 << " ";
  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: " << 70000;
13:        cout <<  endl;
14:        cout << "Here is the sum of 8 and 5: ";
15:        cout << 8+5 << endl;
16:        cout << "Here’s a fraction: ";
17:        cout << (float) 5/8 << endl;
18:        cout << "And a very very big number: ";
19:        cout << (double) 7000 * 7000 << endl;
20:        cout << "Don’t forget to replace Jesse Liberty ";
21:        cout << "with your name... ";
22:        cout << "Jesse Liberty is a C++ programmer! ";
23:        return 0;
24:  }

Image

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, are 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. The 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. HELP.cpp Demonstrates Comments


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

Image


Hello World!
That comment ended!

Image

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

There is a third style of comment that 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.

Functions

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 on Day 5, “Organizing into Functions.” The types that can be returned from a function are covered in more detail on Day 3, “Working with Variables and Constants.” The information provided today 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>
  2:  
  3:  // function Demonstration Function
  4:  // prints out a useful message
  5:  void DemonstrationFunction()
  6:  {
  7:        std::cout << "In Demonstration Function ";
  8:  }
  9:  
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 " ;
16:        DemonstrationFunction();
17:        std::cout << "Back in main ";
18:        return 0;
19:  }

Image


In main
In Demonstration Function
Back in main

Image

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 on Day 3.

Listing 2.7. FUNC.cpp Demonstrates a Simple Function


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

Image


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
Exiting...

Image

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 few days.

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 terms used is the term method. Method is simply another term for functions that are part of a class.

Summary

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.

Q&A

Q   What does #include do?

A   This is a directive to the preprocessor, which 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.

Q   What is the difference between // comments and /* style comments?

A   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.

Q   What differentiates a good comment from a bad comment?

A   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.

Workshop

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 you understand the answers before continuing to tomorrow’s lesson.

Quiz

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?

Exercises

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151