Call by reference in C++ with example


Reference are nothing but constant pointers. References are automatically de-referenced by the compiler. A reference, as the name suggests, is like an alias. Call it by any name, it references to the same entity. References must always be initialized. The pointer used for reference pointing is called the reference and the actual variable is called the referent. Changing a reference changes referent.

C++ Program to call by address function

#include<iostream> using namespace std; void swap(int &a, int &b){ int z; z = a; a = b; b = z; } int main(){ int a = 3, b = 5; cout<<"Before :"<<a<<","<<b<<endl; swap(a,b); cout<<"After :"<<a<<","<<b; return 0; }

Output:-

Before :3,5
After :5,3

Explanation of the program

The above function converts into:
void swap(int* const a, int* const b){
int z;
z=*a;
*a=*b;
*b=z;
}
The result would be same as that of Call by address. A reference is like a pointer. But, there is a slight difference between the two.