Datasheet
When run, this code will output a random value from memory for the first line and the number 7 for the
second. This code also shows how variables can be used with output streams.
The table that follows shows the most common variable types used in C++.
Type Description Usage
int Positive and negative integers (range int i = 7;
depends on compiler settings)
short Short integer (usually 2 bytes) short s = 13;
long Long integer (usually 4 bytes) long l = -7;
unsigned int Limits the preceding types to unsigned int i =2;
unsigned short
values >= 0 unsigned short s = 23;
unsigned long unsigned long l = 5400;
float
Floating-point and double precision float f = 7.2;
double
numbers double d = 7.2
char A single character char ch = ‘m’;
bool true or false (same as non-0 or 0) bool b = true;
Variables can be converted to other types by casting them. For example, an int can be cast to a bool.
C++ provides three ways of explicitly changing the type of a variable. The first method is a holdover
from C, but is still the most commonly used. The second method seems more natural at first but is rarely
seen. The third method is the most verbose, but often considered the cleanest.
bool someBool = (bool)someInt; // method 1
bool someBool = bool(someInt); // method 2
bool someBool = static_cast<bool>(someInt); // method 3
The result will be false if the integer was 0 and true otherwise. In some contexts, variables can be
automatically cast, or coerced. For example, a
short can be automatically converted into a long because
a
long represents the same type of data with additional precision.
long someLong = someShort; // no explicit cast needed
When automatically casting variables, you need to be aware of the potential loss of data. For example,
casting a
float to an int throws away information (the fractional part of the number). Many compilers
C++ does not provide a basic string type. However, a standard implementation of a
string is provided as part of the standard library as described later in this chapter
and in Chapter 13.
7
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 7