In C language, exchanging the values of two variables is usually implemented through a function called "Swap". The purpose of this function is to interchange the values of two variables. The following is an implementation of a simple exchange function and an explanation of its principle:
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5;
int y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
// 调用交换函数
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
This exchange function (swap
) takes a pointer as a parameter and modifies the value of the actual variable through the pointer. The following is an explanation of the principle of this function:
-
Parameter passing: The function uses pointers as parameters, which means that the address of the variable is passed to the function instead of the actual value. In this example,
int *a
andint *b
are the addresses of variablesx
andy
respectively. -
Temporary variable: Inside the function, use a temporary variable
temp
to store the value of a variable so that the data is not lost during exchange. -
Exchange process: By using the pointer operator
*
, the value pointed to bya
is stored in a>temp
, then assign the value pointed to byb
toa
, and finally assign the value pointed bytemp
Assign tob
. -
Call example: In the
main
function, we declare two variablesx
and < a i=4>, and print their values. The function is then called, exchanging their values by passing and , their addresses. Finally, print and again, and you can see that their values have been exchanged.y
swap
&x
&y
x
y
This type of exchange through pointers avoids the memory overhead of passing large data structures, because only the address of the variable is actually passed rather than the entire data.