C Swap Function: Swapping Two Numbers
In C language, you can swap the values of two numbers by customizing a swap function, which is typically named “swap”. Below is an example code:
#include <stdio.h>
// 定义交换函数
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 10;
int num2 = 20;
printf("交换前:num1 = %d, num2 = %d\n", num1, num2);
// 调用交换函数
swap(&num1, &num2);
printf("交换后:num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
In the code above, swapping two numbers can be achieved by calling the swap function and passing in the addresses of the two variables. In the swap function, the value of the first number is first stored in a temporary variable, then the value of the second number is assigned to the first number, and finally, the value of the temporary variable is assigned to the second number, thus completing the swapping of the two numbers.