[C language] Three ways to swap the values of two numbers

        In the process of learning C language for the first time, my understanding of C language is not deep enough. I think this solution is very powerful. After all, a simple exchange of two numbers can be written with computer logic and run correctly...

intmain()
{
    int num1 = 10;
    int num2 = 20;
    int tmp = 0;

    tmp = num1;
    num1 = num2;
    num2 = tmp;

    return 0;
}

        However, through these two days of study, I found that the former method is not perfect in practice. This code will create a temporary variable during the running process, occupying an extra memory space. The use of memory is wasteful.

        Here is a new algorithm I learned about:

intmain()
{
    int num1 = 10;
    int num2 = 20;

    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    return 0;
}

        This is not the end, when I touch the in-place operation, here I learned a more powerful algorithm through learning.

intmain()
{
    int num1 = 10;
    int num2 = 20;

    num1 = num1^num2;
    num2 = num1^num2;
    num1 = num1^num2;

    return 0;
}

    The same is the exchange of two numerical values. The C language implements the same function through different algorithms, which is great for one problem and multiple solutions. The charm of C is really not just that he can implement arbitrary functions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325562713&siteId=291194637