0

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';
    }
}
3

2 Answers 2

3

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;
      |               ^
Sign up to request clarification or add additional context in comments.

5 Comments

why it is behaving different if we didn't define a int x = 5 ? [output :] godbolt.org/z/39oooPT1a
That regrettably is what undefined behaviour means. Your program isn't correct (x is used unitialized) so it may give you any output it wants. In general just be sure to compile your code without warnings, they really do matter.
@PepijnKramer ok, then why isn't compiling ? code link is mention in above comments ?
@JituDeRaps Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The progam may just crash.
@JituDeRaps C++ It is one of the features of C++, it allows for very fine control but it also expects you (as a developer) to know what you are doing. And C++ expects you to initialize your variables. For example setting memory to 0 you are going to overwrite is extra work and C++ is not going to do that implicitly for you. Where possible C++ gives warnings (as it does in this case). For the rest you will have to write unit tests, and use code analysis tools.
-2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.