对于int a 和 int b
可以使用下面的代码 互换a和b的值
void function(inta, int
b){
a=a+b;
b=a-b;
a=a-b;
}
如果交换 两个char类型,该怎么办喃?
大家讲道理2017-04-17 14:46:40
The char type is actually a byte type, with only one byte, so the issue of overflow must be considered, and addition cannot be used.
Of course, in fact, int types cannot be exchanged by addition and subtraction. Using 位异或
is a general method.
void main()
{
char a = 'x';
char b = 'y';
a ^= b;
b ^= b;
a ^= b;
std::cout << "a:"<< a <<"-b:" << b<<std::endl;
//a:y-b:x
}
If you are on the windows platform, you can use built-in functions
void main()
{
char a = 'x';
char b = 'y';
b=InterlockedExchange8(&a, b);
std::cout << "a:"<< a <<"-b:" << b<<std::endl;
//a:y-b:x
}
You can use assembly to do it directly by yourself
void main()
{
char a = 'x';
char b = 'y';
__asm
{
mov al,a
xchg al,b
mov a,al
}
std::cout << "a:"<< a <<"-b:" << b<<std::endl;
//a:y-b:x
}
阿神2017-04-17 14:46:40
char
It’s actually int
#include <stdio.h>
void swap(char *a, char *b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main() {
char a = 'x';
char b = 'y';
printf("交换前: a='%c', b='%c'.\n", a, b);
swap(&a, &b);
printf("交换后: a='%c', b='%c'.\n", a, b);
return 0;
}
Output
交换前: a='x', b='y'.
交换后: a='y', b='x'.
怪我咯2017-04-17 14:46:40
Remember, bit operations are used. I forgot the details
Mark it and wait for the master to answer it
伊谢尔伦2017-04-17 14:46:40
void function(char &a, char &b){
if(a==b) return ;
a = a ^ b;
b = b ^ a;
a = a ^ b;
}
In fact, for 2 integers (including char), using XOR to exchange variables is better than using addition and subtraction (there is no overflow problem)
PHP中文网2017-04-17 14:46:40
Using XOR is not efficient/space-saving, and the result is wrong when two char
are equal. For example:
char a = 'f';
char b = 'f';
char a = b ^ a // now a == 0
And when it comes to assembly, there is no extra space. Please refer to Why it is wrong to use XOR to exchange variables
伊谢尔伦2017-04-17 14:46:40
Type conversion is required
So when converting char type data,
must refer to an intermediate third variable of type int
So the question you asked is contradictory. Can't be achieved.