首页 > 其他 > 详细

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

时间:2020-04-13 10:46:15      阅读:61      评论:0      收藏:0      [点我收藏+]

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;
}

 

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

原文:https://www.cnblogs.com/weiyouqing/p/12689264.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!