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

_Generic Keyword ใน C11: Generic Selection

_Generic (C11) เลือก expression ตามชนิดข้อมูลของ controlling expression ใช้สร้าง type-generic macros

Syntax

_Generic(controlling-expression, type1: expr1, type2: expr2, ..., default: exprN)

ตัวอย่าง: Macro ตรวจสอบชนิด

#define TYPE_CHECK(x) _Generic((x), \
    char: 1, int: 2, long: 3, \
    float: 4, double: 5, \
    default: 0)

int main() {
    printf("%d\n", TYPE_CHECK('a'));     // 1
    printf("%d\n", TYPE_CHECK(123));     // 2
    printf("%d\n", TYPE_CHECK(123L));    // 3
    printf("%d\n", TYPE_CHECK(3.14f));   // 4
    printf("%d\n", TYPE_CHECK(3.14));    // 5
    printf("%d\n", TYPE_CHECK("str"));   // 0 (default)
    return 0;
}

ประโยชน์

  • เขียน macro ที่ทำงานต่างกันตาม type (เช่น print, compare, math functions)
  • ลดการใช้ void* และ casting
  • Type safety ดีกว่า