Variable Scope defines the region in a C++ program wherein a variable is accessible.

The scope of the variable is determined by the place where it is declared.

 

There are three ways to declare a variable in C++:

  1. Inside a function or a block which is called local variables, 
  2. In the definition of function parameters which is called formal parameters. 
  3. Outside of all functions which is called global variables. 

 

We will learn about functions and parameters in the later chapters, but as of now, we will throw some light on local and global variables.

 

Local Variables:

The variables that are declared inside a function have a scope local to that function only.

So, if a variable is declared inside a particular function then it will be accessible by the statements inside the function’s body only. Such variables are thus known as the local variables.

 

For Example:

#include <iostream> 

void main () 

{ 

// Local variable declaration: 

int a, b; 

int c; 

// actual initialization 

a = 10; 

b = 20; 

c = a + b; 

cout << c;

}

Here, a, b and c are local variables for the main function, they are only accessible inside the main function and any statement written outside this function’s body cannot use them.

 

Global Variables:

A variable that is declared outside of all the functions are accessible by all the functions of the program. Such kinds of variables have their scope throughout the code, and are called the Global Variables.

 

For Example:

#include <iostream> 

// Global variable declaration: 

int g=5,h=20; 

void main () 

{ 

// Local variable declaration: 

int a, b;

int g=10;

// actual initialization 

a = 10; 

b = 20; 

cout << g<<endl<<h<<endl<<a<<endl<<b; 

}

Here, g is first declared as a global variable and then as a local variable, while, h is a global variable. a and b are local variables.

 So, when the above code executes, the output will be:

Output

10 // Value of g

20// Value of h

10//Value of a

20// Value of b

Explanation

  1. Here, the value of g is taken to be 10, because when a variable with a same name is declared both globally and locally as well, then the local declaration is given more preference.
  2. After that value of h is 20 as it is initialized globally.
  3. Then values of a and b are printed as they are.

Note: endl is used to add a new blank line while printing in C++.

 

Initialization of Variables:

Local Variables need to be initialized by the coder, but the Global Variables are automatically given these default values on declaration.

Data Type  Value 
int 
char  ‘\0’ 
float 
double 
pointer  NULL 

 

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019