ต่อไปนี้คือตัวอย่างการสลับสองตัวแปร
ตัวอย่าง
#include <stdio.h>
int main() {
int a,b;
printf("Enter the value of a : ");
scanf("%d", &a);
printf("\nEnter the value of b : ");
scanf("%d", &b);
a += b -= a = b - a;
printf("\nAfter Swapping : %d\t%d", a, b);
return 0;
} ผลลัพธ์
Enter the value of a : 23 Enter the value of b : 43 After Swapping : 4323
ในโปรแกรมด้านบนนี้ ตัวแปร a และ b สองตัวถูกประกาศและเริ่มต้นแบบไดนามิก ณ รันไทม์
int a,b;
printf("Enter the value of a : ");
scanf("%d", &a);
printf("\nEnter the value of b : ");
scanf("%d", &b); มีการสลับตัวเลขโดยไม่ต้องใช้ตัวแปรตัวที่สาม
a += b -= a = b - a;