next up previous
Next: The string class Up: A Second C++ Program: Previous: The real code

Explanation of the Program

The program consists of several statements. The statements are executed in the order in which they appear, starting from the first.

  int age;
  char name[10];

These are declaration statements for the variables age and name. Variables are also called identifiers. All identifiers in C++ must be declared before they are used. All must have a datatype. Here age is an integer and name is a string of characters of maximum length $10 - 1 = 9$. The commonly used basic datatypes in C++ and the number of bits they use on our system are
datatype description
int Integer (32 bits)
float Floating point (32 bits)
double Floating point (64 bits)
char Single character (8 bits = 1 byte)

To get more than one character we specified the length in brackets [] after the name. We asked for 10 characters, but the last one (a null character) is reserved to indicate the end of the string, so only 9 are available. The brackets make name the name of an array. We will discuss arrays later. For now, simply use this pattern for char strings.

The names age and name are our own invention. Variable names are composed of upper and lower case letters (case sensitive), digits, and the underscore _ character. They must begin with a letter but can be of any length with modern compilers. A couple dozen names are reserved by the compiler. For example int and char are used to specify the datatype, so they can't be used for names. Other names, such as cout and cin, are already in use for other purposes, so they, too, can't be used.

  cout << "enter name and age: \n";

It is always a good idea to prompt the user for data about to be read from the keyboard. Otherwise, it isn't clear whether the program is failing or simply waiting for input.

  cin >> name >> age;

This is the way iostream provides for reading data from the Unix standard input device (usually the keyboard). You could split this statement in two:
  cin >> name;
  cin >> age;
and it would do the same thing. The >> in this context causes the keyboard words to be converted and stored as the specified type. As a mnemonic, the >> can be thought of as pointing in the direction of the data flow.

  cout << "Your name is " << name
       << " and age is " << age << "\n";

Note that a character string can be written either as a literal constant enclosed in double quotes or as a multicharacter variable (character array) as in name. Just as cin did, cout lets us string together multiple output values with << between each of them.

Notice that this single statement is broken into two lines for readability. The compiler ignores line breaks in statements. That is why the semicolon is required to signal the actual end of the statement.

next up previous
Next: The string class Up: A Second C++ Program: Previous: The real code
Carleton DeTar 2008-09-03