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

ตัวดำเนินการ Increment และ Decrement ใน C#

ตัวดำเนินการ Increment (++) และ Decrement (--) ใน C#

ใช้เพิ่ม/ลดค่าตัวแปรจำนวนเต็มทีละ 1 มี 2 รูปแบบ: **Prefix** (หน้า) และ **Postfix** (หลัง)

Prefix (++x, --x) - Pre-increment/Pre-decrement

  • เพิ่ม/ลดค่า **ก่อน** แล้วคืนค่าใหม่
  • ค่าของนิพจน์ = ค่าหลังเปลี่ยน

Postfix (x++, x--) - Post-increment/Post-decrement

  • คืนค่า **ปัจจุบัน** ก่อน แล้วค่อยเพิ่ม/ลด
  • ค่าของนิพจน์ = ค่าก่อนเปลี่ยน

ตัวอย่างแสดงความแตกต่าง


using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("=== PREFIX (++a) ===");
        int a = 10;
        Console.WriteLine($"a = {a}");
        Console.WriteLine($"++a = {++a}"); // a=11, คืน 11
        Console.WriteLine($"a = {a}");   // 11
        
        Console.WriteLine("\n=== POSTFIX (a++) ===");
        int b = 10;
        Console.WriteLine($"b = {b}");
        Console.WriteLine($"b++ = {b++}"); // คืน 10, แล้ว b=11
        Console.WriteLine($"b = {b}");    // 11

        Console.WriteLine("\n=== ในนิพจน์ซับซ้อน ===");
        int x = 5;
        int y = ++x + x++; // ++x = 6, x++ = 6 (คืน 6 แล้ว x=7)
        // y = 6 + 6 = 12, x = 7
        Console.WriteLine($"x = {x}, y = {y}");
    }
}

ผลลัพธ์


=== PREFIX (++a) ===
a = 10
++a = 11
a = 11

=== POSTFIX (a++) ===
b = 10
b++ = 10
b = 11

=== ในนิพจน์ซับซ้อน ===
x = 7, y = 12

Decrement Operators


int a = 10;
Console.WriteLine(--a); // 9 (prefix)
Console.WriteLine(a);   // 9

int b = 10;
Console.WriteLine(b--); // 10 (postfix)
Console.WriteLine(b);   // 9

ตารางสรุป

Operatorชื่อลำดับการทำงานค่าของนิพจน์
++xPre-incrementเพิ่ม → คืนค่าค่าใหม่
x++Post-incrementคืนค่า → เพิ่มค่าเก่า
--xPre-decrementลด → คืนค่าค่าใหม่
x--Post-decrementคืนค่า → ลดค่าเก่า

ใช้กับชนิดข้อมูลใดได้บ้าง?

  • Integer types: sbyte, byte, short, ushort, int, uint, long, ulong
  • Floating-point: float, double, decimal
  • Enum (underlying integral type)
  • Pointer types (unsafe context)
  • Custom types ที่ overload operator ++/--

หลักการหลีกเลี่ยง Bug

  1. หลีกเลี่ยงใช้ในนิพจน์ซับซ้อน - แยกบรรทัดให้ชัดเจน
  2. ใช้ Prefix เป็นค่าเริ่มต้น (++i) ในลูป for - ประสิทธิภาพดีกว่าเล็กน้อย (ไม่ต้องเก็บค่าเก่า)
  3. เข้าใจลำดับ Evaluation - C# evaluate left-to-right

// ✅ ดี - ชัดเจน
for (int i = 0; i < 10; ++i) { ... }

// ❌ ระวัง - ยากอ่าน
int a = 5;
int b = a++ + ++a + a++; // Confusing!

// ✅ ดี - แยกบรรทัด
int a = 5;
int temp1 = a++; // 5
int temp2 = ++a; // 7
int temp3 = a++; // 7
int b = temp1 + temp2 + temp3; // 19

Overloading ++/-- ใน Custom Type


public struct Counter
{
    public int Value { get; private set; }
    
    public static Counter operator ++(Counter c)
    {
        return new Counter { Value = c.Value + 1 };
    }
    
    public static Counter operator --(Counter c)
    {
        return new Counter { Value = c.Value - 1 };
    }
}