Reference Variable In C++
Reference variable in C++
A reference variable is an alias to the existing variable, or it is just the other name to the variable. the reference variable points to the same memory address as the variable. any change done using the reference variable will change the original variable. we can use any of them to refer to the variable.
To understand this concept think that a variable is labeled by the name, let's say 'i' in the memory location, the reference variable is just the second label to that memory location. so we can access the value stored in that variable using the original variable or the reference variable.
for Example:
int i = 17;
int& reference = i;
Here the & is not read as as address or ampersand it is read as reference. here is an example how the reference variable works.
#include <iostream> using namespace std; int main () { // declare simple variable int i; // declare reference variable int& r = i; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl; return 0; }
output:
Value of i : 5 Value of i reference : 5
References are usually used for function argument lists and function return values. So following are two important topics related to Reference variables.
- Return by reference
- Call by reference or reference as parameter.
This two will be covered in the next blogs.
Comments
Post a Comment
if you have any doubts, let me know