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';
}
}
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;
| ^
Because when you declare int &x = x;
you initialise a variable x with itself, as it shadow the other x
variables.
You get 1 but could get anything.
try int &y = x;
instead