C language: exchange the values of 2 numbers without introducing a third variable (2 methods)

First, let me show you the general way of introducing a third variable to exchange the value of two numbers:

#include<stdio.h>
int main()
{
    int a = 3, b = 5, t;
    t = a;
    a = b;
    b = t;
    printf("a=%d ,b=%d", a, b);
    return 0;
    
}

Of course, you can also introduce pointers to exchange the values ​​of two numbers. There are many ways to exchange the values ​​of two numbers. I will not list them here. Next, I will list two methods without introducing variables:

Method One: Addition and Subtraction

However, this method is only suitable for calculations with smaller numbers. If the number is too large, stack overflow is prone to occur.

#include<stdio.h>
int main()
{
    int a = 3, b = 5;
    a = a + b;
    b = a - b;
    a = a - b;
    printf("a=%d,b=%d", a, b);
    return 0;
}

Method 2: XOR method

#include<stdio.h>
int main()
{
    int a = 3, b = 5;
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    printf("a=%d,b=%d", a, b);
    return 0;
}

The two methods need to be calculated and passed. You can practice by yourself and calculate it again. If you don’t understand the method two XOR symbols (^), you can read my other blog, which explains the usage of XOR symbols http : //t.csdn.cn/fcTHf

Guess you like

Origin blog.csdn.net/m0_75115696/article/details/128846901