0

I need assistance in understanding why reference variables are used in C++. The reference variables points to other variables since they are an alias of other variable We are able to create

int x = 10;
int y = x;

Why do we use it? It serves the same purpose as a reference. I'm learning C++ as a beginner. Please assist in figuring out why we chose &y = x rather than y = x for the preceding solution.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    Do you know why you might want a reference in the first place? Have you seen how they're used in arguments? `y = x` is a copy, not a reference. `&y = x` is a reference. – tadman Dec 30 '22 at 14:30
  • There's nothing in your example code to show why you'd ever choose the reference `int &y = x;` over the copy, because your example code doesn't _do_ anything. In general, some ideas about organizing and structuring code may be hard to understand before you actually have some code to organize and structure. – Useless Dec 30 '22 at 15:31
  • Your example is not the same as if you use a reference - add `y = 20;` in both cases and then inspect the value of `x`. (A reference refers to an *object*, not to a variable. If you write `int& y = x;`, "x" and "y" are different names for the same `int`.) – molbdnilo Dec 30 '22 at 15:48
  • 1
    This is explained in any beginner [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Dec 30 '22 at 15:50

2 Answers2

3

The variable is not the same as the value it holds. If

int x = 5;
int y = 5;

then x and y have the same value but are completely different variables with distinct addresses.

But

int x = 5;
int &y = x;

Now y is an alias to x, means they are the same variable with different names, meaning they have the same address in memory. Hope this helps.

Vahan
  • 166
  • 13
3

The difference is following:

int x = 10;
int y = x;
y = 5; // After this line x == 10

int& z = x;
z = 5; // After this line x == 5
sklott
  • 2,634
  • 6
  • 17