Loading...
C++

Variable Scope

While writing code we need various variables. Each variable have their own boundaries where they are accessible. Variables does not hold their values outside their boundaries. These boundaries are known as scope of variables. It is important to know the scope and lifetime of the variable. The Variable Scope can be divided into two categories.

1. Global Variable
2. Local Variable

1. Global Variable:

The variables which are declared outside the main() function are called as Global variables. The variable scope is the full file where the variable is defined. The global variable are defined as given below:

#include<iostream.h>
using namespace std;
int weight; //This is Global Variable
int main()
{
weight=3
cout<<“Weight is “<<weight<<endl;
cin.ignore();
return 0;
}

2. Local Variable:

Global variables can be accessed in the full file but, local variables are not accessed in the full file. The local variables’s scope is within the block of instruction that is defined between “{” and “}”. For example:

#include<iostream.h>
using namespace std;
int main()
{
int a=2, b=3;
c=a+b;
cout<<c;
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *