The C language implements the value of exchanging two numbers

Source: Internet
Author: User

There are many ways to exchange two-digit values in C, as described below.

Do not use intermediate variables:

1 //xor, A^=b^=a^=b;2A ^=b;3b ^=A;4A ^=b;5 6 //Add and Subtract7A = a +b;8b = A-b;9A = A-b;Ten  One //multiplication AA = A *b; -b = A/b; -b = A/b;

Use intermediate variables:

1 // Temporary space required 2 temp = A; 3 a = b; 4 b = temp;

As you might think, the code shown above simply describes the idea of exchanging two-digit values, and there are many places to be aware of when you actually use them. You can choose the macro to implement, or the function is implemented, the following one by one for you.

Macro implementation:

1 #define 2     (a) ^=3     (b) ^=4     (a) ^= (b)

Note: The macro implementation is primarily for a value that does not use intermediate variables to exchange two numbers, the above code only describes the XOR, and so on.

Function implementation:

1 //Error Implementation2 voidSwapintAintb)3 {4     inttemp =0;5temp =A;6A =b;7b =temp;8 9     return;Ten } One  A //Correct Implementation - voidSwapint*a,int*b) - { the     inttemp =0; -temp = *A; -*a = *b; -*b =temp; +  -     return; +}

Note: Function implementations are applicable to using intermediate variables and not using intermediate variables.

Analysis:

Error implementation is due to a and B as the formal parameters, in the function of the exchange, but there is no effect on the external arguments, the real ability to achieve the exchange of two values is the correct implementation shown, because the parameter is two pointers, the pointer is the address, when the exchange is the value of the two address is exchanged, when the function is finished, The exchange of two values is realized.

The C language implements the value of exchanging two numbers

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.