Expected output : 5
Doesn't want to create a reference to itself.
#include <iostream>
int x = 3;
int main()
{
int x = 5;
{
int &x = ::x; // how to create a reference to int x = 5;
std::cout << x << '\n';
}
}
This is undefined behavior. When you initialize the reference, the symbol x is already overloaded to refer to the reference.
If you enable all warnings you'll get something like this (gcc -Wall):
<source>: In function 'int main()':
<source>:9:15: warning: reference 'x' is initialized with itself [-Winit-self]
9 | int &x = x;
| ^
<source>:7:9: warning: unused variable 'x' [-Wunused-variable]
7 | int x = 5;
| ^
<source>:9:15: warning: 'x' is used uninitialized [-Wuninitialized]
9 | int &x = x;
| ^
<source>:9:15: note: 'x' was declared here
9 | int &x = x;
| ^
int x = 5 ? [output :] godbolt.org/z/39oooPT1a
xshadows the two outerxs, just as the middlexshadows the outermostx.