Thursday, May 2, 2019

Variable in c++

Variable in C++

 Variable is define as a name which is associated with a value that can be changed. Variable are used to store the data into it.  

 For example:

Let us think that I ask you to retain the number 5 in your mental memory, and then I ask you to memorial also the number 2 at the same time. You have just stored two different values in your memory. Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Values that we could now for example subtract and obtain 4 as result.
The whole process that you have just done with your mental memory is a simile of what a computer can do with two variables. The same process can be expressed in C++ with the following instruction set:
                      a = 5;              
                      b = 2;              
                     a = a + 1; .       
                      result = a - b;



Syntax of declaring a variable in C++

data_type variable1_name = value1, variable2_name = value2;
For example:
                int a=5, b=2
We can also write it like this:
int a,b;
a=5;
b=2;

Types of variables


Variables can be categorised based on their data type. For example, in the above example we have seen integer types variables.

Following are the types of variable  available in C++.
• int type variable
• float type variable
•double type variable
•char type variable
•string type variable


Types of variables based on their scope

Before going in details of data type lets discuss what is scope first. When we discussed the Hello. World Program, we have seen the curly braces in the program like this:-
#include<iostream>

using namespace std;

int main()
{
   
   cout<<"Hello World!";

   return 0;
}


Any variable declared inside these curly braces have scope limited within these curly braces, if you declare a variable in main() function and try to use that variable outside main() function then you will get compilation error.

There are two types of variables based on scope:


Local variable: Local variable is one declared within the body of a function or a block.







Global variable:   global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a program.





No comments:

Post a Comment

Array

Arrays  An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by ad...