Now that you understand the rules for naming a variable, and you understand the concept
of a data type, you are ready to learn how to declare a variable. In C++, you must declare all
variables before you can use them in a program. When you declare a variable, you tell the
compiler that you are going to use the variable. In the process of declaring a variable, you
must specify the variable’s name and its data type. Declaring a variable tells the compiler
that it needs to reserve a memory location for the variable. A line of code that declares a
variable is known as a variable declaration. The C++ syntax for a variable declaration is
as follows:
dataType variableName;
For example, the following declaration statement declares a variable named counter of the
int data type:
int counter;
The compiler reserves the amount of memory space allotted to an int variable (32 bits,
or 4 bytes) for the variable named counter. The compiler then assigns the new variable
a specific memory address. In Figure 2-1, the memory address for the variable named
counter is 1000, although you wouldn’t typically know the memory address of the
variables included in your C++ programs.
15
counter (variable name) another variable
value of counter value of the next variable
first
byte
second
byte
third
byte
fourth
byte
1000 (The memory address is assigned by
the compiler; you cannot assign the memory
address yourself.)
1004 (This is the next available memory address
after counter because 4 bytes [1000, 1001, 1002,
and 1003] have been reserved for the variable named
counter.)
You can also initialize a C++ variable when you declare it. When you initialize a C++ variable,
you give it an initial value. For example, you can assign an initial value of 8 to the counter
variable when you declare it, as shown in the following code:
int counter = 8;
You can also declare and initialize variables of data type double and string variables
(objects) as shown in the following code:
double salary;
double cost = 12.95;
string firstName;
string homeAddress = "123 Main Street";
You can declare more than one variable in one statement as long as they have the same data
type. For example, the following statement declares two variables, named counter and value.
Both variables are of the int data type.
int counter, value;
0 comments:
Post a Comment