Daily question: the third variable is not applicable and two input parameters are exchanged.
Problem description: Write a function swap and input two parameters A and B. The third variable cannot be used in the function, and the and B after the function output is switched.
Train of Thought: IfProgramIf the third variable cannot be used, it can only be implemented through the so-called "technique. The technique used here is as follows: a ^ 0 = A. A ^ A = 0 (exclusive or operation)
ImplementationCode:
# Include < Stdio. h >
# Include < Stdlib. h >
// Exchange two data, but not the third variable
Void Swap ( Int * A, Int * B)
{
* B = ( * A) ^ ( * B );
* A = ( * A) ^ ( * B );
* B = ( * A) ^ ( * B );
}
Int Main ()
{
Int A = 3 ;
Int B = 4 ;
Printf ( " Before swap, A = % d, B = % d \ n " , A, B );
Swap ( & A, & B );
Printf ( " After swap, A = % d, B = % d \ n " , A, B );
Return 0 ;
}