Variables in C++

Variables in C++ :

Variables are the containers to store Data.


Syntax :

 Data_type Variable_name = value;  

Variables can be of various types (Data_type)


Data Types in C++ are catagorised in 3 groups:

   1.Built-in = int, float, char, Boolean, Double.

   2.User-defined=struct, union, enum.

   3.Derived=Arrays, Functions, Pointers.


 Built-in Datatypes:

*Integer -> 0,1,2,3,4 

Example:

   int Data=3;


*Float ->1.2,1.3,1.4

Example: 

   float Data=1.2;


*Character -> 'a','b','c'

Example:

   char Data='a';


*Boolean -> 0 or 1,Yes or No

Example:

   bool a=0;


 Based on Scope Variables are defined into two types:

      1.Local  Variables

      2.Global Variables


Local Variables :

Variables are  defined within a function or block are said to be local to those functions.

Anything between ‘{‘ and ‘}’ is said to inside a block.

Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block.

Declaring local variables: 

Local variables are declared inside a block.

 

Example:

 #include<iostream>  
 using namespace std;  
 void Func()  
 {     
   int Num=18;    
 }  
  int main()  
 {  
   cout<<"Number is: "<<Num;     
   return 0;  
 }  
 ----Output------  
 Error: Num was not declared in this scope  

The above program displays an error saying “ Num was not declared in this scope ”.  

 

From the above Program

Num variable is declared in Func() Function it is 'Local' to the Func() Function Only.

   

Global Variables :

Global Variables can be accessed from any part of the program.

They are available through out the life time of a program.

They are declared at the top of the program outside all of the functions or blocks.

Declaring global variables:

Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program

Example:

 #include<iostream>  
 using namespace std;  
 int global = 10;  
 void display()  
 {  
   cout<<global<<endl;  
 }  
 // main function  
 int main()  
 {  
   display();    
   global = 20;  
   display();  
 }  
 ------Output------  
 10  
 20  

In the program, the variable “global” is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program.


 Rules to Declare a Variables :

1.It should be in range from  1  to 255 characters.

2.Must begin with a "Letter" or "Underscore".

3.After the first Letter, Variable names can also contain letters and numbers.

4.NO special characters are allowed.

5.Case Sensitive.

6.Cannot use reserved keywords to Name Variables.


Note :

We can use both Local and Global Variables have same name BUT Local takes the precedence.


AUTHOR : Rakshit Joshi [ Linkedin Profile ]

For Videos Join Our Youtube Channel: Join Now