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