Daily question: the third variable is not applicable and two input parameters are exchanged.

Source: Internet
Author: User
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 ;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.