What is the output of the given program? #include <iostream> using namespace…

20252025

What is the output of the given program?

#include <iostream>
using namespace std;

int x = 10;

void fun()
{
    int x = 2;
    {
        int x = 1;
        cout << ::x << endl;
    }
}

int main()
{
    fun();
    return 0;
}

Answer: C. 10Concept: The unary scope resolution operator :: prefixed to an identifier (::name) always resolves that name in the global namespace, ignoring any local or…

  1. A.

    1

  2. B.

    2

  3. C.

    10

  4. D.

    error

Attempted by 80 students.

Show answer & explanation

Correct answer: C

Concept: The unary scope resolution operator :: prefixed to an identifier (::name) always resolves that name in the global namespace, ignoring any local or enclosing-block variable that shares the same name. This lets code inside a nested block reach the outermost (global) declaration even when intervening blocks redeclare (shadow) the same identifier.

  1. The program declares three separate variables named x: a global x = 10 at file scope, a local x = 2 inside fun(), and an innermost-block local x = 1 inside the nested braces.

  2. An unqualified x written inside the innermost block would resolve to the closest enclosing declaration - the innermost local x = 1 - because an inner block's declaration shadows every outer declaration of the same name.

  3. The statement instead writes ::x, not x. The leading :: explicitly requests the global-namespace x, bypassing both local shadows (the innermost x = 1 and fun()'s x = 2) regardless of how many blocks lie between the statement and the global declaration.

  4. So cout << ::x prints the value of the global variable, which is 10.

This is confirmed by the code's dependence on that global declaration: if the file-scope line int x = 10; were removed, ::x would have no global x to bind to and the program would fail to compile - showing the printed value 10 comes specifically from that global declaration, not from either local one.

Explore the full course: Nta Ugc Net Paper 2

Loading lesson…