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 (string, floating-point, 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 string type in C++ is called string
. The following statement creates a new variable named fred that has
This kind of statement is called a declaration. The type of a variable
determines what kind of values it can store. A
string variable can contain strings, and it should come as no surprise
that int variables can store integers. To create an integer variable,
the syntax is:
In C++, there are two floating-point types, called float and double. In
this book we will use doubles exclusively.
The syntax for a floating-point variable is:
To declare a character
variable you suppose to use keyword int:
here fred, bob, mike and sam are just arbitrary names you made up for
the variable to identify it. 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:
int iHour, iMinute;
you could probably
make a good guess at what values would be stored in them. In this
example the first small letter (s, c, i or d) indicate a variable type
and the remaining part says something about variable meaning (note:
this is only a convention for this book, not a general feature of C++).
This example also demonstrates the syntax for declaring multiple
variables with the same type: iHour and iMinute are both integers (int
You have also seen values like
. These are actually boolean values and there is a special type of
for them. We will learn about this type later.
C++ is generally considered a “loosely typed” language, unlike languages
such as Ada which has much stricter type syntax. However, even though
general C++ is somewhat forgiving with regard to variable types, and
the WCM C++ implementation even more so, if your intent is to progress
to general purpose programming, it is very important that you
understand the concept and implications of the “type” concept.