– are the named location in store (RAM) where we store or put value (s) that may change any time during the program execution.
The variable must have
– a name
– a data type
– the named location (variable) must exists in RAM
– there must be a value in that named location in RAM.
The type indicates the type of value that can be stored in that store.
C++ allows the declaration of variable anywhere in the scope (to be discussed later).
This means that a variable can be declared right at the place of its first use.
This makes the program easier to understand because the variables are declared in the context of their use
The general format for variable declaration is:
datatype varname1[, varname2,….]
Example: int a;
The above statement declares a variable of type int that is, only int type data can be stored in the variable or named location a. If you don’t specify the data type, it is default to int type.
The following example declares a and b are both of type int
Use useful/meaningful variable names
variable names a, b and x is meaningless. Always use names those who have appropriate meaning and any non-programmer can understand the meaning of the variable.
More examples on variable declarations are:
float salary, net_pay;
int empID, empage, no_of_children;
double yrs_budget, yrs_expenditure;
unsigned long population;
-Means giving initial value to a variable
If you don’t give any value to a variable, you will get garbage value.
-Before the use of the variable, you must initialize your variable.
To initialize var, we use assignment operator(=)
int age; //declares age int data type
age=12; //initialize age to value 12.
// or age is assigned a value 12
// or 12 is assigned to var age
In initialization, we say that put the right-hand-side value to the LHS var.
- The statement
is called assignment statement where, we assign variable age to a value 12.
- In assignment statement, rhs of the assignment operator must be a value or an expression (which will be evaluated to a value before assignment operation).
- For example, int salary=2*basic_pay + med_allowance;
- In the above, the rhs of assignment op. is an expression which will be evaluated first and then assignment operation will take place.
You can declare and initialize a variable at the same time. Example,
The above declares the var max as int type as well as it initializes to a value 12.
In an assignment statement, the lhs must be a variable.
const int x=12;
In the above, x is declared as constant.
In the assignment statement, lhs x is a constant which violates the rule of the assignment statement. I
n this case, computer will give an error.
Data/Variable types in C++
Data types in C++ can be classified under various categories as shown below:
We are reached:variable,Variable initialization,assignment statement,data type in C++,Fundamental data type,modifiers,range of difference data type,some useful variable name,general format of variable.