I l@ve RuBoard Previous Section Next Section

1.1 How to Write a C++ Program

We've been asked to write a simple program to write a message to the user's terminal asking her to type in her name. Then we read the name she enters, store the name so that we can use it later, and, finally, greet the user by name.

OK, so where do we start? We start in the same place every C++ program starts ?in a function called main(). main() is a user-implemented function of the following general form:



int main() 


{ 


   // our program code goes here 


} 

int is a C++ language keyword. Keywords are predefined names given special meaning within the language. int represents a built-in integer data type. (I have much more to say about data types in the next section.)

A function is an independent code sequence that performs some computation. It consists of four parts: the return type, the function name, the parameter list, and the function body. Let's briefly look at each part in turn.

The return type of the function usually represents the result of the computation. main() has an integer return type. The value returned by main() indicates whether our program is successful. By convention, main() returns 0 to indicate success. A nonzero return value indicates something went wrong.

The name of a function is chosen by the programmer and ideally should give some sense of what the function does. min() and sort(), for example, are pretty good function names. f() and g() are not as good. Why? Because they are less informative as to what the functions do.

main is not a language keyword. The compilation system that executes our C++ programs, however, expects a main() function to be defined. If we forget to provide one, our program will not run.

The parameter list of a function is enclosed in parentheses and is placed after the name of the function. An empty parameter list, such as that of main(), indicates that the function accepts no parameters.

The parameter list is typically a comma-separated list of types that the user can pass to the function when the function is executed. (We say that the user has called, or invoked, a function.) For example, if we write a function min() to return the smaller of two values, its parameter list would identify the types of the two values we want to compare. A min() function to compare two integer values might be defined as follows:



int min( int val1, int val2 ) 


{ 


   // the program code goes here ... 


} 

The body of the function is enclosed in curly braces ({}). It holds the code sequence that provides the computation of the function. The double forward slash (//) represents a comment, a programmer's annotation on some aspect of the code. It is intended for readers of the program and is discarded during compilation. Everything following the double forward slash to the end of the line is treated as a comment.

Our first task is to write a message to the user's terminal. Input and output are not a predefined part of the C++ language. Rather, they are supported by an object-oriented class hierarchy implemented in C++ and provided as part of the C++ standard library.

A class is a user-defined data type. The class mechanism is a method of adding to the data types recognized by our program. An object-oriented class hierarchy defines a family of related class types, such as terminal and file input, terminal and file output, and so on. (We have a lot more to say about classes and object-oriented programming throughout this text.)

C++ predefines a small set of fundamental data types: Boolean, character, integer, and floating point. Although these provide a foundation for all our programming, they are not the focus of our programs. A camera, for example, must have a location in space, which is generally represented by three floating point numbers. A camera also has a viewing orientation, which is also represented by three floating point numbers. There is usually an aspect ratio describing the ratio of the camera viewing width to height. This is represented by a single floating point number.

On the most primitive level, that is, a camera is represented as seven floating point numbers, six of which form two x,y,z coordinate tuples. Programming at this low level requires that we shift our thinking back and forth from the manipulation of the camera abstraction to the corresponding manipulation of the seven floating point values that represent the camera in our program.

The class mechanism allows us to add layers of type abstraction to our programs. For example, we can define a Point3d class to represent location and orientation in space. Similarly, we can define a Camera class containing two Point3d class objects and a floating point value. We're still representing a camera by seven floating point values. The difference is that in our programming we are now directly manipulating the Camera class rather than seven floating point values.

The definition of a class is typically broken into two parts, each represented by a separate file: a header file that provides a declaration of the operations supported by the class, and a program text file that contains the implementation of those operations.

To use a class, we include its header file within our program. The header file makes the class known to the program. The standard C++ input/output library is called the iostream library. It consists of a collection of related classes supporting input and output to the user's terminal and to files. To use the iostream class library, we must include its associated header file:



#include <iostream> 

To write to the user's terminal, we use a predefined class object named cout (pronounced see out). We direct the data we wish cout to write using the output operator (<<), as follows:



cout << "Please enter your first name: "; 

This represents a C++ program statement, the smallest independent unit of a C++ program. It is analogous to a sentence in a natural language. A statement is terminated by a semicolon. Our output statement writes the string literal (marked by double quotation marks) onto the user's terminal. The quotation marks identify the string; they are not displayed on the terminal. The user sees



Please enter your first name: 

Our next task is to read the user's input. Before we can read the name the user types, we must define an object in which to store the information. We define an object by specifying the data type of the object and giving it a name. We've already seen one data type: int. That's hardly a useful way of storing someone's name, however! A more appropriate data type in this case is the standard library string class:



string user_name; 

This defines user_name as an object of the string class. The definition, oddly enough, is called a declaration statement. This statement won't be accepted, however, unless we first make the string class known to the program. We do this by including the string class header file:



#include <string> 

To read input from the user's terminal, we use a predefined class object named cin (pronounced see in). We use the input operator (>>) to direct cin to read data from the user's terminal into an object of the appropriate type:



cin >> user_name; 

The output and input sequence would appear as follows on the user's terminal. (The user's input is highlighted in bold.)



Please enter your first name: anna 

All we've left to do now is to greet the user by name. We want our output to look like this:



Hello, anna ... and goodbye! 

I know, that's not much of a greeting. Still, this is only the first chapter. We'll get a bit more inventive before the end of the book.

To generate our greeting , our first step is to advance the output to the next line. We do this by writing a newline character literal to cout:



cout << '\n'; 

A character literal is marked by a pair of single quotation marks. There are two primary flavors of character literals: printing characters such as the alphabet ('a', 'A', and so on), numbers, and punctuation marks (';', '-', and so on), and nonprinting characters such as a newline ('\n' ) or tab ('\t'). Because there is no literal representation of nonprinting characters, the most common instances, such as the newline and tab, are represented by special two-character sequences.

Now that we've advanced to the next line, we want to generate our Hello:



cout << "Hello, "; 

Next, we need to output the name of the user. That's stored in our string object, user_name. How do we do that? Just the same as with the other types:



cout << user_name; 

Finally, we finish our greeting by saying goodbye (notice that a string literal can be made up of both printing and nonprinting characters):



cout << " ... and goodbye!\n"; 

In general, all the built-in types are output in the same way ?that is, by placing the value on the right-hand side of the output operator. For example,



cout << "3 + 4 = "; 


cout << 3 + 4; 


cout << '\n'; 

generates the following output:



3 + 4 = 7 

As we define new class types for use in our applications, we also provide an instance of the output operator for each class. (We see how to do this in Chapter 4.) This allows users of our class to output individual class objects in exactly the same way as the built-in types.

Rather than write successive output statements on separate lines, we can concatenate them into one compound output statement:



cout << '\n' 


     << "Hello, " 


     << user_name 


     << " ... and goodbye!\n"; 

Finally, we can explicitly end main() with the use of a return statement:



 return 0; 

return is a C++ keyword. The expression following return, in this case 0, represents the result value of the function. Recall that a return value of 0 from main() indicates that the program has executed successfully. [1]

[1] If we don't place an explicit return statement at the end of main(), a return 0; statement is inserted automatically. In the program examples in this book, I do not place an explicit return statement.

Putting the pieces together, here is our first complete C++ program:



#include <iostream> 


#include <string> 


using namespace std; // haven't explained this yet ... 





int main() 


{ 


      string user_name; 


      cout << "Please enter your first name: "; 


      cin >> user_name; 


      cout << '\n' 


           << "Hello, " 


           << user_name 


           << " ... and goodbye!\n"; 





      return 0; 


} 

When compiled and executed, this code produces the following output (my input is highlighted in bold):



Please enter your first name: anna 


Hello, anna ... and goodbye! 

There is one statement I haven't explained:



using namespace std; 

Let's see if I can explain this without scaring you off. (A deep breath is recommended at this point!) Both using and namespace are C++ keywords. std is the name of the standard library namespace. Everything provided within the standard library (such as the string class and the iostream class objects cout and cin) is encapsulated within the std namespace. Of course, your next question is, what is a namespace?

A namespace is a method of packaging library names so that they can be introduced within a user's program environment without also introducing name clashes. (A name clash occurs when there are two entities that have the same name in an application so that the program cannot distinguish between the two. When this happens, the program cannot run until the name clash is resolved.) Namespaces are a way of fencing in the visibility of names.

To use the string class and the iostream class objects cin and cout within our program, we must not only include the string and iostream header files but also make the names within the std namespace visible. The using directive



using namespace std; 

is the simplest method of making names within a namespace visible. (To read about namespaces in more detail, check out either Section 8.5 of [LIPPMAN98] or Section 8.2 of [STROUSTRUP97].)

Exercise 1.1

Enter the main() program, shown earlier. Either type it in directly or download the program; see the Preface for how to acquire the source programs and solutions to exercises. Compile and execute the program on your system.

Exercise 1.2

Comment out the string header file:



// #include <string> 

Now recompile the program. What happens? Now restore the string header and comment out



//using namespace std; 

What happens?

Exercise 1.3

Change the name of main() to my_main() and recompile the program. What happens?

Exercise 1.4

Try to extend the program: (1) Ask the user to enter both a first and last name and (2) modify the output to write out both names.

    I l@ve RuBoard Previous Section Next Section