Variables in C++

What is variables in C++ ?

Variables are nothing but containers for values. Variables tells compiler where to store the value and how much memory to allocate for it.

Declaration of variables in C++

All the variables used in the program must be declared before they are used. The declaration of variables tells compiler how much memory to allocate and create memory address for it. If you do not declare the variable before it is used , compiler will flag an error.

Variable declaration is done like : 
int number;               // To store integer value
char letter;               // To store a character value
float price;               // To store float value
bool isActive;               // To store boolean value

Rules for naming the variables

There are some strict rule to name variables in C++. Violating them would result in compilation error.
1. The first character in variable name should be alphabet or underscore.
2. No commas or blank spaces are allowed within the variable name.
3. No special symbols (like &,*% etc ) other than underscore ( _ ) can be used in variable name.

 Valid declaration of variables
 int number;
 int Pagenumber;
 int  _value;
 int  page_number;
 Invalid declaration of variables
 int 1number;
 int %value;
 int @color;

Initializing the variables

Assigning the value to the variable at the time of declaration is called initialization of variable. If variable is not initialized , it pickups any garbage value.
Variables are initialized as follows :
int value = 10;
bool isCorrect = true;
float price = 0;

 

Types of variables

The scope of a variable is the accessibility of that variable within that program. 
There are two types of variables depending upon their scope : i. Global variables ii. Local Variables

 i. Global variables : These variables are accessible from any function of a program. Global variables are generally declared just after the opening bracket of main function.

ii. Local Variables : The scope of these variables is limited to only for that function only. These are declared inside the function where it is to be use. They are inaccessible from another function.