不用第三个变量交换两个数的值

jackxiang 2008-9-9 16:26 | |
用栈的先进后出:

#include <stdio.h>

int main() {
    int i,j;

    printf("please input two numbers:\n");
    scanf("%d %d",&i,&j);

    printf("the first number i is: %d \n",i);
    printf("the second number j is: %d \n",j);
  
  
    asm ("pushl %%eax\n\t"
         "pushl %%ebx\n\t"
         "popl  %%eax\n\t"
         "popl  %%ebx"
         :"=a"(i),"=b"(j)
         :"a"(i), "b"(j));
  
  
    printf("after swap \n");
    printf("the first number i is: %d \n",i);
    printf("the first number j is: %d \n",j);
  
}


用异或:(RAID里面就用到了这技术。三个里面知道任意两个就可以恢复第三个)


    #define swap(a, b) (a) ^= (b), (b) ^= (a), (a) ^= (b)

    #include <stdio.h>

    int main(void)
    {
        int ival1 = 10, ival2 = 20;

        printf("%d %d\n", ival1, ival2);
        swap(ival1, ival2);
        printf("%d %d\n", ival1, ival2);
    }



作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/1231/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]