C language uses macros to implement 2 variable Exchange

Source: Internet
Author: User
Tags time 0

Documenting which methods are more pervasive and more efficient does not include methods that use functions, and using pointers is more appropriate if you use functions.

    •   Using intermediate variables

Shaped as int tmp, TMP = A; A=b; b = tmp;

1 #define SWAP (A, b) {typeof(a) _t=A; A=B; b=_t;}

The only drawback is the need for additional stack space.

    •   Using arithmetic methods

1 #define SWAP (x, y) (x) = (x) + (y); (y) = (x)-(y);(x) = (x)-(y);

cannot be used, x+y can cause data overflow, then it is finished, and can only operate on basic data types, construction data types cannot be used.

    •   The cost of brain-different or law

1 #define SWAP (x, y) (x) ^= (y); (y) ^= (x);(x) ^= (y);

Can only be manipulated for basic data types and cannot be used for construction data types.

Then compare the efficiency of 1,3, using 2 macros to run the following code:

int Main (intconstChar *argv[]) {    int0xFFFFFFF ;         int 5 ;     int Ten ;      while (k-- )    {        SWAP (A, b);    }     return 0 ;}

Using time./main timing, the Xor method takes 2.2-2.4s, the intermediate variable method time 0.7-0.8s, the efficiency increases 3 times times.

C language uses macros to implement exchange of 2 variables

Related Article

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.