The principle of Swap function in C language

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:

  1. 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 and int *b are the addresses of variables x and y respectively.

  2. Temporary variable: Inside the function, use a temporary variabletemp to store the value of a variable so that the data is not lost during exchange.

  3. Exchange process: By using the pointer operator*, the value pointed to by a is stored in a>temp, then assign the value pointed to by b to a, and finally assign the value pointed by temp Assign tob.

  4. Call example: In the main function, we declare two variables x 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. yswap&x&yxy

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.

Guess you like

Origin blog.csdn.net/m0_64476561/article/details/134367573