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. 10 — Concept: The unary scope resolution operator :: prefixed to an identifier (::name) always resolves that name in the global namespace, ignoring any local or…
- A.
1
- B.
2
- C.
10
- 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.
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.
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.
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.
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.