Scope Resolution Operator in C++

In C,Suppose there are two variables with the same name 'c'.Assume that one is declared outside the function(global) and another is declared locally inside the function.
If we attempt to access variable 'c' inside the function we always access the local variable.Basic rule says that whenever there is conflict between local variable and global variable,the local variable gets the priority.

C++ allows you flexibility of accessing both the variables using scope resolution operator(::).

Example:
             #include<iostream.h>
             int x=10;
             void main()
             {
                       int x=20;
                       cout<<"First"<<x<<::x;
                       {
                             int x=30;
                             cout<<"Second"<<x<<::x;
                       }
                       cout<<"Third"<<x<<::x;
             }
             
             OutPut:
                         20  10
                         30  10
                         20  10

3 comments:

  1. :: always referes to the global X. is there any way to access the value of X in main. i.e. from the inner block where X = 30, can we read the access the value of X in the immediate outer scope. I mean X = 20 .. Please suggest

    ReplyDelete
  2. :: always referes to the global X. is there any way to access the value of X in main. i.e. from the inner block where X = 30, can we read the access the value of X in the immediate outer scope. I mean X = 20 .. Please suggest

    ReplyDelete
  3. Please do more articles like this in the future. Very informational and knowledgeable. I will expect more from you in the future. For now i will just bookmark your page and surely I'm gonna come back later to read more. Thank you to the writer!


    www.imarksweb.org

    ReplyDelete