What is Variable?

C++ Programming Tutorial

What is Variable?


The Variable is also the name of a memory location. It stores the values of data types. Its value can be changed and it can be reused many times.






Rules for the variable name.

  1. It is case-sensitive. For eg int 'a' and int 'A' these are different variables.

  2. A variable starts with any alphabet (a-z, A-Z) or underscore (_). But didn't start with a digit.

  3. A Variables can be named alphanumeric and '_'. For eg. a1 = 5, var1, var2,_var3.

  4. The variable does not allow white space.

  5. The variable name is not any C ++ keywords name.


The syntax for the Variable Declaration.

type variable_list;

The declaring a variable is given below.

int x; float y; char ch;

Here x, y and ch are variables, and int, float, char are data types.

For example:

int x; int y;

Then declare as int x, y; are Same data type variables.

int x; float y;

The declare as int x and float y. Different data type variables.

We can also provide values while declaring the variables as given below:

int x=10,y=20; //declaring 2 variable of integer type float ft=30.8; //declaring 1 variable of float type char ch='P'; //declaring 1 variable of char type

Valid variable names:

int x; int _xy; int p31; float m; float _pq; float r36; char c; char _ch; char c31;

Invalid variable names:

int 20; // A variable name didn't start with a digit. int x y; // A variable does not allow white space. int char; // A variable name is not any C ++ keywords name.

Declaration and initialization of C++ Variable.

When Variable declare, then this variable allocates memory according to the data type.After being a variable declare, it takes a Garbage Value inside itself.

Garbage Value: Garbage Value Variable is given by the Compiler.

#include <iostream> using namespace std; int main(){ int number; cout<<"Value of number : "<<number; return 0; }
Output:
Value of number : 4354190

Note: Here 4354190 is a garbage value.

#include <iostream> using namespace std; int main(){ int no1, no2, no3; cout<<"Value of no1 : "<<no1<<endl; cout<<"Value of no2 : "<<no2<<endl; cout<<"Value of no3 : "<<no3<<endl; return 0; }
Output:
Value of no1 : 4354318 Value of no2 : 2293652 Value of no3 : 4354224

Note: Here no1,no2 and no3 variables are store garbage value respectively 4354318, 2293652 and 4354224.

Variable Initialization

When Variable initializes, then this variable allocates memory, according to the data type it is. For eg. int for 2bytes (16-bit) | 4bytes (32-bit) | 8bytes (64-bit).

In variable initialization, a variable takes only one value for eg. int x = 5;

#include <iostream> using namespace std; int main() { int number1 = 5, number2 = 6; cout<<"Value of number1 : "<< number1<<endl; cout<<"Value of number1 : "<< number2; return 0; }
Output:
Value of number1 : 5 Value of number1 : 6