Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

สลับค่าตัวแปรสองตัวในบรรทัดเดียวใน C/C++

สามารถสลับค่าตัวแปรสองตัวได้ในบรรทัดเดียว (One-liner) หลายวิธี

วิธีที่ 1: Arithmetic Method

a += b -= a = b - a;

การทำงาน (a=28, b=8)

1. a = b - a    → a = 8 - 28 = -20
2. b -= a       → b = 8 - (-20) = 28
3. a += b       → a = -20 + 28 = 8
Result: a=8, b=28 ✓

วิธีที่ 2: XOR Swap (Bitwise)

(a ^= b), (b ^= a), (a ^= b);

การทำงาน (a=8, b=28)

1. a ^= b  → a = 8 ^ 28 = 20
2. b ^= a  → b = 28 ^ 20 = 8
3. a ^= b  → a = 20 ^ 8 = 28
Result: a=28, b=8 ✓ (กลับสู่ค่าเดิม)

ตัวอย่างโปรแกรมครบ

#include <stdio.h>

int main() {
    int a = 28, b = 8;
    printf("Before: a=%d, b=%d\n", a, b);
    
    // Method 1
    a += b -= a = b - a;
    printf("Method 1: a=%d, b=%d\n", a, b);
    
    // Method 2
    (a ^= b), (b ^= a), (a ^= b);
    printf("Method 2: a=%d, b=%d\n", a, b);
    
    return 0;
}

ผลลัพธ์

Before: a=28, b=8
Method 1: a=8, b=28
Method 2: a=28, b=8

วิธีอื่นๆ

// 3. Compound Literal (C99) - สร้าง Temporary Array
a = (int[2]){b, a}[0];  // a = b, แต่ต้องมี temp อยู่ดี

// 4. GNU Extension (Statement Expression) - GCC/Clang เท่านั้น
({ int t = a; a = b; b = t; });

// 5. C++17 Structured Binding (ไม่ใช่ 1 line แต่สวย)
auto [x, y] = std::pair{b, a};  // x=b, y=a

ข้อควรระวัง

แนวทางแนะนำ (Best Practice)

// C: ใช้ Temp Variable - ชัดเจน เร็ว ปลอดภัย
int temp = a;
a = b;
b = temp;

// C++: ใช้ std::swap (Optimized, Type-safe, Noexcept)
#include <algorithm>
std::swap(a, b);

// หรือ Member Swap
a.swap(b);  // สำหรับ Containers, Strings

สรุป

One-liner Swaps เป็น Tricks ที่น่าสนใจสำหรับการแข่งขัน/สัมภาษณ์ แต่ใน Production Code ควรใช้ std::swap (C++) หรือ Temp Variable (C) เพื่อความชัดเจน ความปลอดภัย และประสิทธิภาพ (Compiler Optimize ได้ดีกว่า)

วิธีข้อจำกัด
ArithmeticInteger Overflow Risk, ไม่ได้กับ Float
XORInteger เท่านั้น, Aliasing Bug (a และ b ชี้ที่เดียวกัน → 0)
ทั้งคู่Undefined Behavior ใน C++ หาก Modify Object ซ้ำระหว่าง Sequence Points (Pre-C++17)