Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Call by Reference

C++ Call by Reference

C++ Function C++ functions

pass arguments to a function via thecall by referencemethod, which copies the reference's address to the formal parameter. Inside the function, that reference is used to access the actual argument used in the call. This means modifying the formal parameter affects the actual argument.

To pass a value by reference, the parameter reference is passed to the function just like passing any other value. Therefore, correspondingly, in the function below swap() , you need to declare the function parameter as a reference type; this function is used to swap the values of the two integer variables pointed to by the parameters.


// Function definition
void swap(int &x, int &y)
{
   int temp;
   temp = x; /* 保存地址 x 的值 */
   x = y;    /* 把 y 赋值给 x */
   y = temp; /* 把 x 赋值给 y  */
  
   return;
}

Now, let us call the function by passing values by reference swap():

Example

#include

<
iostream
using
namespace
std

;

// Function declaration

void

swap

(

int

&

x

,

int

&

y

)

;

int

main

(

)

{

// local variable declaration

int

a

=

100

;

int

b

=

200

;

cout

<<

"

Before swap, value of a:

"

<<

a

<<

endl

;

cout

<<

"

Before swap, value of b:

"

<<

b

<<

endl

;

/*

Call the function to swap values

*/

swap

(

a

,

b

)

;

cout

<<

"

After swap, value of a:

"

<<

a

<<

endl

;

cout

<<

"

After swap, value of b:

"

<<

b

<<

endl

;

return

0

;

}

// Function definition

void

swap

(

int

&

x

,

int

&

y

)

{

int

temp

;

temp

=

x

;

/*

Save the value at address x

*/

x

=

y

;

/*

Assign y to x

*/

y

=

temp

;

/*

Assign x to y

*/

return

;

}

When the code above is compiled and executed, it produces the following result:


交换前,a 的值: 100
交换前,b 的值: 200
交换后,a 的值: 200
交换后,b 的值: 100

Key points

  1. Reference definition: by using the&symbol to define a reference type, for exampleint &ref.
  2. Passing by reference: using a reference type in the function parameter list, so that modifications inside the function affect the actually passed variable.
  3. Avoiding copy overhead: pass-by-reference avoids the copy overhead when passing large objects, improving efficiency.

Use cases for call by reference

Call by reference is an important technique in C++ that improves code efficiency and flexibility. Understanding and proficiently using call by reference is very helpful for writing efficient C++ programs.

C++ Function C++ functions