Pass by reference

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. C onlyIn C, the corresponding parameter in the called function must be declared as a pointer type. C++ only In C++, the corresponding parameter can be declared as any reference type, not just a pointer type.

In this way, the value of the argument in the calling function can be modified by the called function.

The following example shows how arguments are passed by reference. In C++, the reference parameters are initialized with the actual arguments when the function is called. In C, the pointer parameters are initialized with pointer values when the function is called.

C++ only
#include <stdio.h>

void swapnum(int &i, int &j) {
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swapnum(a, b);
  printf("A is %d and B is %d\n", a, b);
  return 0;
}
End of C++ only
C only
#include <stdio.h>

void swapnum(int *i, int *j) {
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swapnum(&a, &b);
  printf("A is %d and B is %d\n", a, b);
  return 0;
}
End of C only

When the function swapnum() is called, the actual values of the variables a and b are exchanged because they are passed by reference. The output is:

A is 20 and B is 10
C++ only

In order to modify a reference that is const-qualified, you must cast away its constness with the const_cast operator. The following example demonstrates this:

#include <iostream>
using namespace std;

void f(const int& x) {
  int* y = const_cast<int>(&x);
  (*y)++;
}

int main() {
  int a = 5;
  f(a);
  cout << a << endl;
}

This example outputs 6.

End of C++ only

Related information