×

C++ Variable Types



What are Variables in C++?

Like human memory , Computer memory has millions of cells where it can store data or information. Now to retreive an information from those cells , each cell should be given one name called as 'variable name'. These variables are mostly useful and can be of different types like integer, float , double , char, strings.

What is variable declaration ?

Variable declaration means we just create a variable and memory will hold some space for that variable. We did not given any value yet just declared a variable.

Example :-
int a;
int b;
float c;

What is variable definition ?

Variable definition means we assigned some value to a variable.

Example :-
int a = 10;
int b = 20;
int c = 30;
float d = 12.0;
char a = "A";

What happens in memory when we declare a variable ?

int a =10;
int b = 20;
int c = 30;

Types of variables

There are two types of variables :

1) Local variables

2) Global variables

What are local variables ?

Local variables persist value only inside a block. If you try to use a local variable outside a block of function or method you will see a compile error.

Example :-

#include <iostream>
using namespace std;
/* Global value a = 20; */ 
int a = 20;
int main() {

  cout<<"Global value of a is "<<a<<"\n";
  /* Local value of a */   
  int a = 10;
  cout<<"Local value of a is "<<a;
  return 0;
}

Output :-

Global Value of a is 20
Local value of a is 10

Variable 'a' assigned with value 20 is global variable. That means it is visible in the entire program . Anywhere in any function you can access it. But more closer you are more priority you will get . This is the philosophy of variables :) Inside a main function we assigned a variable 'a' with value 20 thats why it's next print statement printed the value 20.