Variables
Sample program
// Definition and use of variables #include <iostream> using namespace std; int gVar1; // Global variables, int gVar2 = 2; // explicit initialization int main() { char ch('A'); // Local variable being initialized // or: char ch = 'A'; cout << "Value of gVar1: " << gVar1 << endl; cout << "Value of gVar2: " << gVar2 << endl; cout << "Character in ch: " << ch << endl; int sum, number = 3; // Local variables with // and without initialization sum = number + 5; cout << "Value of sum: " << sum << endl; return 0; }
HINT |
Both strings and all other values of fundamental types can
be output with cout. Integers are printed in decimal
format by default.
|
Screen output
Value of gVar1: 0 Value of gVar2: 2 Character in ch: A Value of sum: 8
Data such as numbers, characters, or even complete records are
stored in variables to enable their processing by a
program. Variables are also referred to as objects,
particularly if they belong to a class.
Defining Variables
A variable must be defined before you can use it in a
program. When you define a variable the type is specified
and an appropriate amount of memory reserved. This memory space is addressed by
reference to the name of the variable. A simple definition has the following
syntax:
Syntax:
typ name1 [name2 ... ];
This defines the names of the variables in the list name1 [, name2 ...] as variables of the type type. The parentheses [ ... ] in the
syntax description indicate that this part is optional and can be omitted. Thus,
one or more variables can be stated within a single definition.
Examples:
char c; int i, counter; double x, y, size;
In a program, variables can be defined either within the program's
functions or outside of them. This has the following effect:
-
a variable defined outside of each function is global, i.e. it can be used by all functions
-
a variable defined within a function is local, i.e. it can be used only in that function.
Local variables are normally defined immediately after the
first brace—for example at the beginning of a function. However, they can be
defined wherever a statement is permitted. This means that variables can be
defined immediately before they are used by the program.
Initialization
A variable can be initialized, i.e. a value can be assigned
to the variable, during its definition. Initialization is achieved by placing
the following immediately after the name of the variable:
-
an equals sign ( = ) and an initial value for the variable or
-
round brackets containing the value of the variable.
Examples:
char c = 'a'; float x(1.875);
Any global variables not explicitly
initialized default to zero. In contrast, the initial value for any local
variables that you fail to initialize will have an undefined initial
value.
0 Comments