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
}
Special
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
}
Extended
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
}
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.
General
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.Special
If you are on the windows platform, you can use built-in functions
Extended
You can use assembly to do it directly by yourself
char
It’s actuallyint
Output
Remember, bit operations are used. I forgot the details
Mark it and wait for the master to answer it
In fact, for 2 integers (including char), using XOR to exchange variables is better than using addition and subtraction (there is no overflow problem)
Using XOR is not efficient/space-saving, and the result is wrong when two
char
are equal. For example:And when it comes to assembly, there is no extra space. Please refer to Why it is wrong to use XOR to exchange variables
Char is also an integer in nature
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.