Passing Arguments by Reference

Passing by reference refers to a method of passing arguments where the value of an argument in the calling function can be modified in the called function.

CTo pass an argument by reference, you declare the corresponding parameter with a pointer type.

C++ To pass an argument by reference in C++, the corresponding parameter can be any reference type, not just pointer types.

The following example shows how arguments are passed by reference. Note that reference parameters are initialized with the actual arguments when the function is called.

#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;
}

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

You must define the parameters of swapnum() as references if you want the values of the actual arguments to be modified by the function swapnum().

C++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.

You can modify the values of nonconstant objects through pointer parameters. The following example demonstrates this:

#include <stdio.h>
 
int main(void)
{
  void increment(int *x);
  int count = 5;
 
  /* address of count is passed to the function */
  increment(&count);
  printf("count = %d\n", count);
 
  return(0);
}
 
void increment(int *x)
{
  ++*x;
  printf("*x = %d\n", *x);
}

The following is the output of the above code:

*x = 6
count = 6

The example passes the address of count to increment(). Function increment() increments count through the pointer parameter x.

Related References

IBM Copyright 2003