Coupon Accepted Successfully!


Scope Access Operator

Like C, the variables declared in ‘C++’ programs are totally different from other languages. We can use the same variable names in the ‘C++’ program in separate blocks. The two declarations of the same variable refer different memory locations. When we declare a variable, it is available only to specific part or block of the program. Remaining block or other functions cannot access the variable. The area or block of the ‘C++’ program from where the variable can be accessed is known as the scope of variables.

The scope access (or resolution) operator :: (two colons) allows programmer to access a global (or file duration) name even if it is hidden by a local re-declaration of that name.

4.22 Write a program to use scope access operator. Display the various values of the same variable declared at different scope levels.


Explanation: In the above program, the integer variable ‘a’ is declared before main() and initialized with 10. It is a global variable. In the function main(), re-declaration of ‘a’ is done and this time the variable ‘a’ is initialized with 20. The first cout statement displays the global value of variable ‘a’, that is, 10. In this statement :: scope access operator is used to access the global value of the variable ‘a’. The second cout statement displays the local value of the variable ‘a’, that is, 20. Figure shows the use of scope access operator for accessing global variable.

Description: 144322.png

Scope access operator

Test Your Skills Now!
Take a Quiz now
Reviewer Name