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

4 comments:

  1. At last! I found this truly amazing article. I am very happy that I found this very good article of yours. Very good info and very creative post. Thanks.

    John
    www.imarksweb.org

    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. :: 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
  4. 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