The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Variables

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a named location that stores a value.

Just as there are different types of values (integer, character, etc.), there are different types of variables. When you create a new variable, you have to declare what type it is. For example, the character type in C++ is called char. The following statement creates a new variable named fred that has type char.

    char fred;

This kind of statement is called a declaration.

The type of a variable determines what kind of values it can store. A char variable can contain characters, and it should come as no surprise that int variables can store integers.

There are several types in C++ that can store string values, but we are going to skip that for now (see Chapter 7).

To create an integer variable, the syntax is

  int bob;

where bob is the arbitrary name you made up for the variable. In general, you will want to make up variable names that indicate what you plan to do with the variable. For example, if you saw these variable declarations:

    char firstLetter;
    char lastLetter;
    int hour, minute;

you could probably make a good guess at what values would be stored in them. This example also demonstrates the syntax for declaring multiple variables with the same type: hour and second are both integers (int type).


Last Update: 2005-11-21