Variable In C++


Variable is just a memory location where we can store value. It’s helps in manipulation. We can reuse this variable for many types. Variables are changeable.


Syntax


dataType varName;
Example

int x=10;

int abc123;

int a1;

Not valid

int 12a;

int &23abc;


There are many types of variable in c++.

  1. local variable

  2. gloabal vraiable

  3. static variable

  4. auto variable

  5. external variable

Local Variable


A variable that is create and used within function or block is called local variable.

Example Of Local Variable in C++

#include <iostream>

using namespace std;

int main(){

int a=10;//local variable

cout<<“The value of a is:”<<a;

}


Output:
The value of a is: 10


Global Variable

A variable that is create in top of the program and we can use this variable in any function or block that is called a global variable.

Example Of Global Variable In C++


#include <iostream>

using namespace std;

/* /n use here for new line print message*/

void msg(){

int a=10;//global variable

void msg(){

cout<<“The value of a in msg() \n”<<a;

}


int main(){

cout<<“The value of a is \n”<<a;

msg();

return 0;

}


Output:
The value of a in msg() 10
The value of a is 10


Automatic Variable In C++

auto variable and local variable are same in c programming there is nothing difference between this both are declare within function or block.


Example of Auto Variable In C++


#include <iostream>

using namespace std;

int main(){

int a=10;

auto int b=10;

}


cout<<“The value of a is: %d\n”<<a;

cout<<“The value of a is \n”<<a;

return 0;

}


Output:
The value of a is: 10
The value of b is: 10



Static Variable In C++

A variable that create with static keyword is called static keyword.It’s helps is memory management normally we can say that it save memory.
Example Of Static Variable In C++


#include <iostream>

using namespace std;

/* endl we are using for print statement in new line same as \n */

int a=10; //local variable

static int b=10;//static variable

auto int b=10;

a++;

b++;

cout<<“The value of a is”<<a<<endl;

cout<<“The value of b is”<<b<<endl;

}

int main(){

clrscr();

display();

display();

display();

return 0;

}


Output:
The value of a is 11
The value of b is 11
The value of a is 11
The value of b is 12
The value of a is 11
The value of b is 13

Note:- the local variable print value is 11,11,11,11. But the static variable is print the vaue is 11,12,13 Because it’s not create new memory address for static variable it’s always works with created address.


External variable In C++

A variable that we create for mumtiple files in c++. This technique is most popular for developer we create a variable in files and we use this variable for multiple filse in c++.
Example of external variable in c++
file1.h
extern int a=10;
first.c


#include <iostream>

#include “file1.h”

using namespace std;

int main() {

cout <<“The value of a is” <<a;

}


Output:
The value of a is 10