Three methods and simple analysis of switching Variables

Source: Internet
Author: User

There are two main ways to exchange two variables: With or without temporary variables. The following three simple algorithms are available for detailed operations:

1,Algorithm with temporary variables

#include <stdio.h>int main(void){int a, b, t;scanf("%d%d", &a, &b);t = a;a = b;b = t;printf("a = %d, b = %d\n", a, b);return 0;}


2,Algorithm 1 without the help of temporary variables ( Addition and subtraction)
#include <stdio.h>int main(void){int a, b;scanf("%d%d", &a, &b);a = a + b;b = a - b;a = a - b;printf("a = %d, b = %d\n", a, b);return 0;}


3,Algorithm 2 without the help of temporary variables ( Exclusive or operation)

#include <stdio.h>int main(void){int a, b;scanf("%d%d", &a, &b);a = a ^ b;b = b ^ a;a = a ^ b;printf("a = %d, b = %d\n", a, b);return 0;}
Summary: in normal use, the algorithm with the help of temporary variables is good enough. Algorithms 1 and 2 without the help of temporary variables seem very good (with less than one variable), but they are actually very rarely used, because their applicability is very narrow: only data types that define addition, subtraction, or exclusive operations can be used to improve the ability to read code.

Three methods and simple analysis of switching Variables

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.