CH 04
CH 04
DEFINITION
A variable is a symbolic name for a memory location in which data can be stored and subsequently
recalled. Variables are used for holding data values so that they can be utilized in various
computations in a program. All variables have two important attributes:
The name of a variable is called an identifier. You can give a variable any name you want, as long as
it is a valid identifier.
VALID IDENTIFIERS
A valid identifier is a sequence of one or more letters, digits or underscores. The identifier must begin
with a letter. C++ does not allow identifiers to start with a number, punctuation marks, symbols or
spaces. Compiler specific keywords or external identifiers usually begin with an underscore. It also
possible to use an underscore at the beginning of your identifier, but it is not recommended.
The C++ language is a "case sensitive" language. This means that an identifier with capital letters is
not the same as with normal letters.
For example: myvar, Myvar, MyVar and MYVAR are four different variable identifiers.
The C++ language also uses a set of names that are reserved. It is not allowed to use these keywords
as variable identifiers (variable names). The standard reserved keywords are:
asm, auto, bool, break, case, catch, class, char, const,const_cast, continue, default, delete,
double, do, dynamic_cast, enum, else, explicit, extern, export, float, false, for, friend, goto
int, if, inline, long, mutable, namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, switch, signed, sizeof, static, static_cast, struct, template, this,
throw, true, try, typedef, typeid, typename, union, unsigned, using, void, virtual, volatile,
while, wchar_t
DATA TYPES
• Numeric variables can either be of the type integer (int) or of the type real (float). Integer (int)
values are whole numbers (like 10 or -10.) Real (float) values can have a decimal point in
them. (Like 1.25 or -1.25.)
• Character variables are letters of the alphabet, ASCII characters or numbers (0-9). If you
declare a character variable you must always put the character between single quotes (like so
'a'). So remember a character between single quotes is not the same as a character with single
quotes.
When programming, we store the variables in our computer's memory, but the computer has to know
what kind of data we want to store in them, since it is not going to occupy the same amount of
memory to store a simple number than to store a single letter or a large number, and they are not
going to be interpreted the same way. The memory in our computers is organized in bytes. A byte is
the minimum amount of memory that we can manage in C++. A byte can store a relatively small
amount of data: one single character or a small integer (generally an integer between 0 and 255). In
addition, the computer can manipulate more complex data types that come from grouping several
bytes, such as long numbers or non-integer numbers.
DECLARING A VARIABLE
So we now know different data types and which rules an identifier must comply. But how do we
declare them. Declaring a variable is very easy. First you have to declare the data type. After the data
type you place the name of the variable. But remember choose the names wisely. It is easier if a
variable name reflects the use of that variable. For instance: if you name a float PI, you always know
what it means.
Now let's declare some variables, a variable MyIntegerVariable which is an integer number,
MyRealVariable which is a real number and MyCharacterVariable which is a character variable
respectively.
int MyIntegerVariable;
float MyRealVariable;
char MyCharacterVariable;
The difference between signed and unsigned variables is that signed variables can be either negative
or positive but unsigned variables can only be positive. By using an unsigned variable you can
increase the maximum positive range. When you declare a variable in the normal way it is
automatically a signed variable. To declare an unsigned variable you just put the word unsigned
before your variable declaration or signed for a signed variable although there is no reason to declare
a variable as signed since they already are.
An exception to this general rule is the char type, which exists by itself and is considered a different
fundamental data type from signed char and unsigned char, thought to store characters. You should
use either signed or unsigned if you intend to store numerical values in a char-sized variable.
SCOPE OF VARIABLES
All the variables that we intend to use in a program must have been declared with its type specifier in
an earlier point in the code. Variable can be either of global or local scope. A global variable is a
variable declared in the main body of the source code, outside all functions, while a local variable is
one declared within the body of a function or a block. Global variables can be referred from anywhere
in the code, even inside functions, whenever it is after its declaration.
Example
#include <isostream.h>
using namespace std;
int Integer;
char character; Global variable
char string [20];
int main ()
{
When declaring a regular local variable, its value is by default undetermined. But you may want a
variable to store a concrete value at the same moment that it is declared. In order to do that, you can
initialize the variable. There are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the value to which the
variable will be initialized:
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment
in which it is declared, we could write:
int a = 0;
The other way to initialize variables, known as constructor initialization, is done by enclosing the
initial value between parentheses (()):
For example:
int a (0);
CONSTANTS
The difference between variables and constants is that variables can change their value at any time but
constants can never change their value. The constants value is locked for the duration of the program.
Constants can be very useful; PI for instance is a good example to declare as a constant.
With the pre-processor directive "define" it is possible to define your own constants.
The format of the pre-processor directive #define is:
#define PI 3.14159
With the const prefix you can declare constants with a specific type in the same way as you would do
with a variable:
From the above algorithm we see that we need three variables which all are real numbers. The code
looks like this
1 #include <iostream>
2 using namespace std;
3 #define PI 3.14159 // declaring PI as global variable and initializing it to 3.14
4
5 int main()
6 {
7 float area; // declares a local variable for calculating the area
8 float radius; // declares a local variable for accepting the radius
9 cout << "Welcome, this program calculates area of a circle given radius of a circle \n"; //greeting
10 cout << "Please enter the radius of the circle \n"; // notifies the user to give the program radius
11 cin >> radius; // reads radius form the user and saves it to radius variable
12 area = PI*radius*radius; // calculates area of the circle
13 cout << "The area of the circle equals " << area << " unit square \n"; // displays the output
14 }
Let us try to explain each line indicated by its line number on the left.
line 1. This line uses the preprocessor directive #include to include the contents of the header file iostream in the
program. iostream is a standard C++ header file and contains definitions for input and output.
line 2. This is an advanced feature of C++. It is used to specify that names used in the program (such as cout) are
defined in the standard C and C++ libraries. This is used to avoid problems with other libraries which may
also use these names.
line 3. Declare PI as real number variable with initial value of 3.14. All words after “//” are comments and are
ignored by the C++ compiler.
line 4. Blank lines are also ignored by the C++ compiler.
line 5. This line defines a function called main. A function may have zero or more parameters; these always
appear after the function name, between a pair of brackets. The word void appearing between the brackets
indicates that main has no parameters. A function may also have a return type; this always appears before
the function name. The return type for main is int (i.e., an integer number). All C++ programs must have
exactly one main function. Program execution always begins from main.
line 6. This brace marks the beginning of the body of main.
line 7. Declare area as real number variable for storing the value of the area of the circle after calculation
line 8. Declare radius as real number variable for accepting radius of the circle from the user
line 9. This line is a statement. A statement is a computation step which may produce a value. The end of a
statement is always marked with a semicolon (;). This statement causes the string “Welcome,...." to be sent
to the cout output stream. The last character in this string (\n) is a newline character which is similar to a
carriage return on a type writer. cout is the standard output stream in C++ (standard output usually means
your computer monitor screen) The symbol << is an output operator which takes an output stream as its left
operand and an expression as its right operand, and causes the value of the latter to be sent to the former. In
this case, the effect is that the string "Welcome,…" is sent to cout, causing it to be printed on the computer
monitor screen.
line 10. Same as line 9
line 11. This line reads the input value typed by the user and copies it to radius. The input operator >> takes an
input stream as its left operand (cin is the standard C++ input stream which corresponds to data entered via
the keyboard) and a variable (to which the input data is copied) as its right operand.
line 12. This line is a statement. It computes the area of the circle based on the given information.
line 13. This line outputs the result on your computer monitor.
line 14. This brace marks the end of the body of main.