+ 1
What is reference variable in c++
2 Answers
+ 1
It's like second name for variable. Let's see this example:
int x = 5; //initialise x
int &foo = x; //initialise foo reference with x
x = 20; // change value of x to 20
cout << foo << endl; // foo will show 20 as its value
+ 1
Reference variable is like giving and alias name to a variable. reference variable points to the same address in the memory where the variable is stored. and Reference variables can be only assigned to variables and not to constant values.
Eg:
Suppose we declare int x in our code, now it is stored in memory location 1000, now we use reference variable as below
int &y = x;
here y will also also point to the same memory location where x is stored that is 1000.
hence is we can modify the value at memory location 1000 by using x as well as y.
Suppose u give
int &y=10;
then it will throw compilation error as u r trying to assign reference variable to a constant value.
NOTE: one reference variable can be assigned to only one variable.
Please correct me if m wrong, looking forward for responses.