Several methods of C language data exchange

Source: Internet
Author: User

This is a very common example to implement the exchange of two data a and B. The value of a is given to B and the value of B is given to a. The general practice is to use the intermediate variable cache for exchange. The implementation method is as follows: # include <stdio. h> int main (void) {int a, B, t; scanf ("% d", & a, & B); t = a; a = B; B = t; printf ("% d \ n", a, B); return 0;} the second method is to use force addition without any variables, and then separate them one by one, as follows: # include <stdio. h> int main (void) {int a, B; scanf ("% d", & a, & B); // a = a1, B = b1a = a + B; // a = a1 + b1b = a-B; // B = a1 + b1-b1 => B = a1a = a-B; // a = a1 + b1-(a1 + b1-b1) => a = b1printf ("% d \ n", a, B); return 0 ;} the third method is Pointer exchange, for example: # includ E <stdio. h> int main (void) {int a, B; scanf ("% d", & a, & B); printf ("% d \ n ", b, a); return 0;} another method is the stack mode, which changes the order of the output stack. The Embedded Assembly is as follows: push apush bpop apop B can also use C language to implement the stack function, then complete the exchange between a and B. Summary: There are many implementation methods and their advantages and disadvantages. The first method is commonly used, but there is one more variable. The second method is simple and easy to use. The fourth method is to change the order of the stack to realize switching after the stack features are advanced.

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.