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

while(1) vs while(0) ใน C/C++: Infinite Loop และ Dead Code

while(1) และ while(0) เป็น Idiom พื้นฐานใน C/C++ สำหรับ Loop Control แต่มีความหมายและการใช้งานต่างกันอย่างสิ้นเชิง

while(1): Infinite Loop (Intentional)

  • Condition เป็น Non-zero Constant → Always True
  • ใช้สำหรับ Event Loop, Server Loop, Menu-Driven Programs
  • ต้องมี Break Condition ภายใน Body มิฉะจะ Hang

ตัวอย่าง: Menu Loop

#include <iostream>

int main() {
    int choice;
    while (1) { // Infinite Loop
        std::cout << "\n1. Start\n2. Settings\n3. Exit\nChoice: ";
        std::cin >> choice;
        
        switch (choice) {
            case 1: std::cout << "Starting...\n"; break;
            case 2: std::cout << "Settings...\n"; break;
            case 3: std::cout << "Goodbye!\n"; return 0; // Exit Program
            default: std::cout << "Invalid!\n";
        }
    }
}

while(0): Dead Code / Compile-time Disabled Block

  • Condition เป็น Zero Constant → Always False
  • Body ไม่ถูก Execute เลย (Compiler Optimize ออกไปได้)
  • ใช้ใน Multi-statement Macros เพื่อ Wrap Statements ให้เป็น Single Statement

ตัวอย่าง: Do-While(0) Macro Pattern


// Macro สำหรับ Log หลาย Statement
#define LOG_ERROR(msg) \
    do { \
        fprintf(stderr, "[ERROR] %s:%d: ", __FILE__, __LINE__); \
        fprintf(stderr, msg); \
        fprintf(stderr, "\n"); \
    } while (0)

// Usage: ต้องการ Semicolon ได้เหมือน Statement เดียว
if (error) 
    LOG_ERROR("Failed"); // OK: Single Statement
else
    do_something();     // OK: Else match ได้

หากไม่ใช้ `do { } while(0)` Macro หลาย Statement จะทำให้ `if/else` แพทได้

ตารางเปรียบเทียบ

ด้านwhile(1)while(0)
ConditionTrue (Non-zero)False (Zero)
ExecutionInfinite (จนกว่า Break/Return)Never (Zero Iterations)
Use CaseEvent Loop, Server, MenuMacro Wrapper, Dead Code, Compile-time Disable
Compiler Warningบางครั้ง "Condition is constant"บางครั้ง "Code unreachable"

Modern C++ Alternatives

  • Infinite Loop: for (;;) (Classic), while (true) (Readable)
  • Disabled Code: #if 0 ... #endif (Preprocessor) หรือ if (constexpr false) { } (C++17)
  • Macro Wrapper: do { } while (0) ยังคงเป็น Standard Idiom

สรุป

while(1) = Infinite Loop (ต้องมี Break) while(0) = No-op Loop ใช้ใน Macro Idiom (`do {} while(0)`) เพื่อทำให้ Multi-statement Macro 行為เหมือน Single Statement ทั้งคู่เป็น Idioms ที่นักพัฒนา C/C++ ต้องรู้จัก