• Home
  • C++ Function Call by Reference

C++ Function Call by Reference

In C++, you can pass arguments to a function by reference instead of by value. This means that the function receives a reference to the original argument, rather than a copy of its value.

To pass an argument by reference, you need to use the reference operator (&) in the function definition and the function call. Here is an example of a function that swaps the values of two variables using call by reference:

#include <iostream>
using namespace std;

void swap(int &x, int &y)
int temp = x;
x = y;
y = temp;

int main()
int a = 5, b = 10;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "After swap: a = " << a << ", b = " << b << endl;
return 0;

The output of this program will be:

Before swap: a = 5, b = 10
After swap: a = 10, b = 5

In this example, the swap() function takes two references to integers as arguments. When the function is called, the values of the variables a and b are passed to the function, and the values are swapped.

Passing arguments by reference can be useful when you want to modify the value of the argument in the function and have the change reflected in the calling function. It can also improve the performance of the program by avoiding the overhead of creating and copying function arguments.