为什么不人使用XOR互换? [英] Why don't people use xor swaps?

查看:134
本文介绍了为什么不人使用XOR互换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一个网站,使用XOR互换是快的,因为它不使用一个临时变量。这里有一个例子:

 的#include<&stdio.h中GT;INT主要(无效)
{
    int类型的= 234,B = 789;
    B = ^一个;
    A = B ^一个;
    B = ^一个;
    输出(A =%D,B =%d个,A,B);
    返回0;
}

为什么不使用的人在现实生活中code这个技术?难道只是风格穷呢?有没有明确定义它的东西吗?难道我的编译器可能会从更加清晰code生产,自动优化?


解决方案

  1. 由于可读性preferred了性能。


  2. 由于 TMP =一个; A = B; B = TMP; 不是的的慢


  3. 由于编译器将无论如何优化它。


  4. 由于它的工作原理只有整数。如果你想交换浮点数是什么?字符串?自定义对象?等等。


I read on a site that using xor swaps is fast because it doesn't use a temporary variable. Here's an example:

#include <stdio.h>

int main(void)
{        
    int a=234,b=789;
    b=b^a;
    a=b^a;
    b=b^a;
    printf("a=%d,b=%d",a,b);
    return 0;
}

Why don't people use this technique in real life code? Is it just poor style? Is there something not well defined about it? Is it an optimisation that my compiler might produce from more clear code, automatically?

解决方案

  1. Because readability is preferred over performance.

  2. Because tmp = a; a = b; b = tmp; is not that slow.

  3. Because the compiler will optimize it anyway.

  4. Because it works for integers only. What if you want to swap floating-point numbers? Strings? Custom objects? etc.

这篇关于为什么不人使用XOR互换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆