C语言 如何在C中的一行中交换两个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18394609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to swap two variables in one line in C?
提问by Shaswat
I want to know that is there any other way of swapping 2 numbers in one line and of course without 3rd variable.
我想知道有没有其他方法可以在一行中交换 2 个数字,当然没有第三个变量。
I know one way of doing this:
我知道这样做的一种方法:
b=a+b-(a=b)
or
或者
a=a+b-(b=a)
both are same(approximately). If you know then please help me out.
两者都是相同的(大约)。如果你知道那么请帮助我。
回答by abelenky
The frequently cited classic answer that you are probably looking for is:
您可能正在寻找的经常引用的经典答案是:
a^=b^=a^=b;
But, it is technically wrong, because it changes the same variable more than once before a sequence point.
但是,这在技术上是错误的,因为它在序列点之前不止一次地改变了同一个变量。
回答by Manoj Awasthi
Use bit twiddling in C. Following swap two variables:
在 C 中使用 bit twiddling。以下交换两个变量:
if (a != b) {
a ^= b ^= a ^= b;
}

