Scope resolution operator in C++

Written on:December 30, 2012
Comments are closed

Function of scope resolution operator:

In C++ the scope of a variable is from the point of its declaration till the end of the block in which it is defined. A variable defined outside a block is global whereas the variable defined inside a block is local to the block. If the two variables defined in different scope bear similar name, then the global variable (variable in the outer block) is not accessible from the inner block. To access the global version of the variable, scope resolution operator is used, preceding the variable name.

Consider the following example:-

//some code segment
{             float ans=5;
float ans = 10;
cont << “ans=”<<ans;
cont <<”ans=”<<::ans;

The first output statement results in a value 10, which overrides the global value of a variable, whereas the second output statement fetches the global value of the variable, i.e. 5, as scope resolution operator is used.

Sorry, the comment form is closed at this time.