C calling a function by reference
With pass-by-reference, the formal parameter is a pointer to the address of the actual argument; operating on what the formal parameter points to is equivalent to operating on the actual argument itself.
Passing a pointer allows multiple functions to access the object referenced by the pointer without declaring the object as globally accessible.
/* Function definition */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* 保存地址 x 的值 */
*x = *y; /* Assign y to x */
*y = temp; /* Assign temp to y */
return;
}
For more details about pointers in C, visit C - Pointers section.
Now, let us call the function by passing values by reference swap():
Example
#include
/* Function declaration */
void
swap
(
int
x,
int
y
)
;
int
main
(
)
{
/* Local variable definition */
int
a
=
100
;
int
b
=
200
;
printf
(
"Before swap, value of a: %d\n"
, a
)
;
printf
(
"Before swap, value of b: %d\n"
, b
)
;
/* Call the function to swap values
* &a represents a pointer to a, that is, the address of variable a
* &b represents a pointer to b, that is, the address of variable b
*/
swap
(
&
a,
&
b
)
;
printf
(
"After swap, value of a: %d\n"
, a
)
;
printf
(
"After swap, value of b: %d\n"
, b
)
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
交换前,a 的值: 100
交换前,b 的值: 200
交换后,a 的值: 200
交换后,b 的值: 100
The example above shows that, unlike call-by-value, call-by-reference changes the values of a and b inside the function and actually changes the values of a and b outside the function as well.
C functions