异或交换两个数的值是资源开销最小的方法,不需要中介数,原理简单的来说就是异或的负负得正。
代码:
#include <stdio.h>
int main()
{
int a = 11, b = 22;
printf("a=%d b=%d\n", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a=%d b=%d\n", a, b);
}
编译:
gcc test.c -o test
执行:
a=11 b=22
a=22 b=11
/**
*
* __ (__`\
* (__`\ \\`\
* `\\`\ \\ \
* `\\`\ \\ \
* `\\`\#\\ \#
* \_ ##\_ |##
* (___)(___)##
* (0) (0)`\##
* |~ ~ , \##
* | | \##
* | /\ \## __..---'''''-.._.._
* | | \ `\## _.--' _ `.
* Y | \ `##' \`\ \
* / | \ | `\ \
* /_...___| \ | `\\
* / `. | / ##
* | | | / ####
* | | | / ####
* | () () | \ | | _.-' ##
* `. .' `._. |______..| |-'|
* `------' | | | | | || |
* | | | | | || |
* | | | | | || |
* | | | | | || |
* _____ | | | |____| || |
* / `` |-`/ ` |` |
* \________\__\_______\__\
* """"""""" """""""'"""
* Don't be a fucking stupid donkey! No, this is a fucking mule!
*/