8
#include <iostream>

using namespace std;

int d = 10;

int main()
{
    int d = 20;

    {
        int d = 30;
        cout << d << endl << ::d; // what does it mean?
    }

    return 0;
}

output is:

30
10

I don't understand why "::d" gives 10? Can someone explain it to me please?

2
  • 2
    Because the C++ group wanted to make a language so complex and confusing they would ensure their extreme hourly rates a decade from now because they would be the only ones able to work on the software.. (snark snark). Commented Apr 16, 2012 at 23:47
  • 1
    Same reason why \file.txt is not the same as \subdirectory\file.txt. Commented Apr 17, 2012 at 7:39

1 Answer 1

22

::d means d from global namespace

EDIT: There are three different variables with similar name d. One is in global namespace d=10, one is inside scope of main function (20), and the last one is inside internal block of the main function (30).

Inside every block you have access (by name) to corresponding variable and always have access to the global namespace (by ::).

Sign up to request clarification or add additional context in comments.

4 Comments

But there is 'd=20', why doesnt it change to its value ?
@İbrahimYazıcı There are three scoping levels happening in that code. The global scope, the scope in main() and the scope in the inner most {}. You have three separate variables declared in that program. Not one that you keep reassigning a value to.
@qehgt While you are correct, it might be extremely helpful to others that come across this question if you go into some detail as to the scoping rules and what is really happening in that piece of code.
@Andrew Finnell thanks for the comment, I added more explanations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.