Next: Constants and the declaration
Up: A simple C++ program
Previous: Reserved words
In C++ (as in many other programming languages) all the variables that a program is going to use must be declared prior to use. Declaration of a variable serves two purposes:
For the moment only four variable types are considered, namely, int, float, bool and char. These types hold values as follows:
int
variable by the computer
system and compiler being used. On a PC most compilers allocate
two bytes for each int
which gives a range of -32768 to
+32767. On
workstations, four bytes are usually allocated, giving a range
of -2147483648 to 2147483647. It is important to note that
integers are represented exactly in computer memory.float
variables, this gives an
accuracy of about six significant figures and a range of about
int 123 -56 0 5645 float 16.315 -0.67 31.567 char '+' 'A' 'a' '*' '7'
A typical set of variable declarations that might appear at the beginning of a program could be as follows:
int i, j, count; float sum, product; char ch; bool passed_exam;which declares integer variables
i
, j
and count
, real
variables sum
and product
, a
character variable ch
, and a boolean variable pass_exam
.
type identifier-list;
type specifies the type of the variables being declared.
The identifier-list is a list of the identifiers of the
variables being declared, separated by commas.
Variables may be initialised at the time of declaration by assigning a value to them as in the following example:
int i, j, count = 0; float sum = 0.0, product; char ch = '7'; bool passed_exam = false;which assigns the value 0 to the integer variable
count
and the value
0.0 to the real variable sum
. The character variable ch
is initialised with the character 7
. i
, j
, and
product
have no initial value specified, so the program should
make no assumption about their contents.