Tip:
Highlight text to annotate it
X
Because C++ is a compiled language you have to declare all variables before you can use
them in a program. All variables must have a type too and with every different type you
have to follow certain rules and use specific syntax. Some operations can only be performed
with certain types and might react differently with some types than with others.
How to Declare a Variable Every variable declaration has a very similar
format. First you specify the type and then you specify a variable name. You don’t have
to give the variable a value, but often it is good to give it the equivalent zero value.
The syntax for declaring an integer variable which is called ‘i’:
int i = 1; You have to insert a space between int and
i but the rest of the spaces are optional. The following is the same to the compiler
as the above: int i=1;
The Basic Variable Types There are a lot of different types in C++,
you can even make up your own. But for basic programming you can use integers, decimals
and single characters. The declaration for each of them is as follows:
int i = 1; float i = 1.0;
char i = '1'; A character (char) declaration has to include
the quotation signs around it and can only be one character long. You don’t have to
include the decimal point in your declaration of decimals (float).
Once you have declared a variable you cannot change its type or use the same name for another
variable. Each numeric variable has a limit to its size.
This depends on the compiler, operating system and computer you use. So say the range of
a variable is -256 to 255. If you let that variable be 255 and add one to it it will
then hold -256 as its value. Whenever a variable exceeds its maximum value it cycles around
to the smallest value it can represent. You can declare multiple variables of the
same type by separating them by a comma: int i,j;
Division with Integers and Floats The problem with integer division is that
C++ doesn’t automatically convert integer division to decimal division.
float i; i = 5/2;
Even though i is of the type float the above would assign 2 as the value of i after the
mathematical operation. If you want a decimal result from division one value in the operation
has to be a decimal or a variable of the type float. The following would yield a correct
result: float i;
i = 5.0/2; or
float i; i = 5/2.0;
or float i,j;
j = 5; i = j/2;
Allowed Variable Names There are a few rules about what the name
of a variable can be: Has to start with a letter or an underscore
(_), most other symbols can be used after that
Cannot contain any spaces (space, tab, next line etc)
Certain names are reserved by the compiler, for example ‘int‘ cannot be a variable
name