+2 votes
in Class 11 by kratos

Write a short note on the scope of variables.

1 Answer

+5 votes
by kratos
 
Best answer

A scope is a region of the program and there are three places where variables can be declared:

  • Inside a function or a block which are called local variables,
  • Outside of all functions which are called global variables.

1. Local variables:

Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own.

2. Global variables:

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of a program. A global variable can be accessed by any function. That is, a global variable is available for use throughout the entire program after its declaration.

It should be noted that a program pan have the same name for local and global variables but the value of a local variable inside a function will take preference.

For example,

include

int g_value = 0;

int main()

{

++g_value;

cout<< g_value <<end1;

int g_value= 100;

cout<< “g_value local variable which hides the global one: “ << g_value << end1;

cout<< “g_value global variable: “ << ::g_value << end1; / In case we have a local variable with the same name as a global one, we can access the global variable using the global scope operator. /

return 0;

}

In the above example, we have declared a global variable, g_value, at the beginning of our program, outside any other block. As you can see, we can increment it in the function main and print its value to the screen.

The variables a, b and g value are local variables in the above program. The g_value variable is present in main() also. Now this variable g_value is a local to main() function which will hide the global variable. We can then access the local variable by its name, and as you can see it hides the global variable. Suppose we have to access global variable then we have to use the global scope operator,::, before the variable’* name: ::g_value.

...