Thunfische
Thunfische

Reputation: 1157

" :: " before a variable name c++

#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?

Upvotes: 7

Views: 3955

Answers (1)

qehgt
qehgt

Reputation: 2990

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

Upvotes: 21

Related Questions