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

Pre-increment และ Post-increment กับ Array ในภาษา C


Increment Operators

TypeSyntaxลำดับการทำงาน
Pre-increment++aเพิ่มค่าก่อน → ใช้ค่าใหม่
Post-incrementa++ใช้ค่าเดิมก่อน → เพิ่มค่าทีหลัง

ตัวอย่างที่ 1: กับ Array Element

#include <stdio.h>

int main() {
    int a, b, c;
    int arr[5] = {1, 2, 3, 25, 7};
    
    a = ++arr[1];  // Pre: arr[1] = 2+1=3, a = 3
    b = arr[1]++;  // Post: b = 3, arr[1] = 3+1=4
    c = arr[a++];  // Post: c = arr[3] = 25, a = 3+1=4
    
    printf("%d--%d--%d\n", a, b, c);
    return 0;
}

ผลลัพธ์: 4--3--25

อธิบายขั้นตอน

Initial: arr = [1, 2, 3, 25, 7]

1. a = ++arr[1]
   arr[1] = 2+1 = 3
   a = 3
   arr = [1, 3, 3, 25, 7]

2. b = arr[1]++
   b = arr[1] = 3
   arr[1] = 3+1 = 4
   arr = [1, 4, 3, 25, 7]

3. c = arr[a++]
   a = 3 (current)
   c = arr[3] = 25
   a = 3+1 = 4
   arr = [1, 4, 3, 25, 7]

Final: a=4, b=3, c=25 → Output: 4--3--25

ตัวอย่างที่ 2: Index Out of Bounds Risk

#include <stdio.h>

int main() {
    int a, b, c;
    int arr[5] = {1, 2, 3, 25, 7};
    
    a = ++arr[3];   // arr[3] = 25+1=26, a=26
    b = arr[3]++;   // b=26, arr[3]=27
    c = arr[a++];   // a=26 → arr[26] = OUT OF BOUNDS!
    
    printf("%d--%d--%d\n", a, b, c);
    return 0;
}

ผลลัพธ์: 27--26--0 (ค่า c เป็น Garbage/0 เพราะ Out of Bounds)

⚠️ ข้อควรระวังสำคัญ

  1. Sequence Points - ใน C การแก้ไขตัวแปรเดียวกันมากกว่า 1 ครั้งระหว่าง Sequence Point เป็น **Undefined Behavior**
    
       // ❌ Dangerous - UB
       a[i] = i++;
       // ✅ Safe
       a[i] = i; i++;
       
  2. Array Bounds - Pre/Post increment บน Index อาจทำให้ Index Out of Bounds ได้ง่าย
  3. Readability - โค้ดที่ซับซ้อนด้วย Pre/Post increment ยากต่อการอ่านและ Maintain

Best Practice

  • แยก Increment ออกจากการใช้งาน Array Element
  • ใช้ ++i ใน Loop (Pre-increment มีประสิทธิภาพเท่า Post แต่ชัดเจนกว่า)
  • หลีกเลี่ยง Multiple Side Effects ใน Statement เดียว