+ 3

Regarding declaration

so I want to know suppose I declare int x=5; int &y =x; What exactly is happening with x and y under the hood? Can someone explain me why exactly we are declaring variables in this fashion ? Thanks in advance.

27th Jul 2017, 9:02 AM
Lovish Arora
Lovish Arora - avatar
3 odpowiedzi
+ 6
A reference variable has the same memory address as the item it references. Both x and y will output similar values, and &x and &y will output similar addresses.
27th Jul 2017, 12:28 PM
Hatsy Rei
Hatsy Rei - avatar
+ 10
int x = 5; // We tell the program to store x as a variable somewhere on the stack, give it a value of 5. int &y = x; // We tell the program to store y as a reference to x, meaning that both x and y will access the same address (and the value stored within that address). // This means that x and y refer to the same data. Whatever changes done to either x or y will reflect on both variables because they refer to the same address when you try to access the stored data.
27th Jul 2017, 9:08 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
@Hatsy Rei so you mean to say that both x and y store address to same data. what will be output cout <<x<<y<<&x<<&y;
27th Jul 2017, 9:24 AM
Lovish Arora
Lovish Arora - avatar