不使用第三个变量交换两个变量的值方法

1. 使用宏定义:

#define SWAP(X, Y) (X) += (Y);(Y)=(X)-(Y);(X)=(X)-(Y);

2. 使用异或位操作符

int x = 21;
int y = 12;

x ^= y;
y ^= x;
x ^= y;
#include <stdio.h>
#include <stdlib.h>

int main(int argn ,char *argv[])
{
    int i = 0;
    int j = 0;
    
    if ((++i > 0) || (++j > 0))
    {
        printf("i = %d\n", i);
        printf("j = %d\n", j);
    }

    int x = 21;
    int y = 12;

    x ^= y;
    y ^= x;
    x ^= y;

    printf("here x = %d\n", x);
    printf("here y = %d\n", y);

    SWAP(x,y);

    printf("here x = %d\n", x);
    printf("here y = %d\n", y);
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/weiyouqing/p/12689264.html