Variables in C++

Variables

  • A variable is a memory unit that is capable of storing data which can be modified (rewritten) at any point of time in a program
  • Simply a variable is a name given to a memory location
Variables in C++

Declaring a variable 

  • A variable is created with a certain size(memory allocated) as per the data type specified, the variable must be declared before it is used and for storing data
  • In this  stage, garbage value is stored in the variable

Example 

int a,b,c;

or

int a;
int b;
int c;
float k; 

Example program to demonstrate variable declaration 

#include <iostream>
using namespace std;
int main()
{
int a; //variable declaration
   cout << "a value:" << a<< endl; //garbage value
   cout << "address of a:" << &a << endl; //a's assigned address
cout << "size of a: " << sizeof(a) <<"bytes"; //allocated memory in bytes

return 0;

Output

a value:0
address of a:0x6ffe0c
size of a: bytes4

Variable Initialization

In this stage, the user assigns value as per the requirement within the memory bounds i.e garbage value is overridden 

Example

a = 10;
f = 78.9; 

Example program to demonstrate variable initialization

#include <iostream>
using namespace std;

int main()
{ int a; //variable declaration cout << "a value:" << a << endl; a = 3; //variable initialization cout << "a value:" <<a << endl; a = 5 + a; //data overriding cout << "a value:" << a <<endl;

return 0;

Declaration cum initialization 

Variable can be initialized at the time of declaration itself 

Example 

int a = 10;
int a, b, c = 10;/*  Only c is initialized with 10 and a and b remain uninitialized and contains garbage values*/ 

Chained initialization

Above program will raise an error because only ‘a’ has been declared ‘b’ and ‘c’ remain undeclared but still we have used as a part of initialization. hence we must be careful and ensure that all the variables are  declared before they have been used

Example

int main()
{
       int a=b=c=0;
       //or
       /* assignment operator evaluates from right to left
       c=0;
       b=c;
       a=b;
       */
      cout << a << "\n" << b << "\n" << c;

return 0; }

O/P 

ERROR: 'a' was not declared 
ERROR: 'b'  was not declared 

To resolve the above declare a and b as follows 

int b,c;
int a = b = c = 0;