Variable is the place to store the piece of information.
A D V E R T I S E M E N T
As one might store the
friend's phone number in own memory, we can store this information in the
computer's memory. These are the means of accessing the computer's memory.
There are fairly strict rules on how the variables are named which C++ imposes:
Variable names should start with the letter.
The variable names are case-sensitive (i.e., variable "myNumber" is different
from "MYNUMBER" which inturn is different from "mYnUmBeR").
Variable names cannot have blank spaces in between.
A variable names cannot have the special characters.
Variable types
Variables are of three basic types which are as follows:
int
float
char
Declaring the Variables
Variable type is nothing but a description of the kind of the information a variable
will store. Declaring the variable in C++ is simple. Let us say that we want to declare
the variable of type int called "myAge". That is to say, Variable myAge will store
the integer, Variable myName will store an character, Variable myHeight will store
float value. In C++, this is written as shown below:
int myAge;
char myName;
float myHeight;
How to Type Cast the Variable?
In C++ Casting is easy. Let us say that we have used a float variable storing the
number like "26.3141885", and we want to have the int storing an integer portion
instead of the float. This is done as shown below:
int GetAverage()
{
// assume that regularAvg and specialAvg store two floats
float totalAvg = regularAvg + specialAvg;
// cast totalAvg to an int
int truncatedAvg = (int) totalAvg;
// return the truncated value
return truncatedAvg;
}
The key part to notice here is the line of code which reads int truncatedAvg = (int)
totalAvg. What we are doing here is taking the float, totalAverage, that stores some
kind of the decimal number (say 82.41832), and getting rid of ".41832" part by casting
it to the int. This works since int is the only capable of storing the integers, so it
simply stores an integer portion of the totalAvg.