Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Từ khóa _Generic trong C (C11)

Giới thiệu

_Generic (C11) cho phép định nghĩa macro chọn triển khai dựa trên kiểu dữ liệu của biểu thức. Tạo được generic programming trong C.

Cú pháp

_Generic( expression,
    type1: value1,
    type2: value2,
    ...
    default: default_value
)

Ví dụ: Macro kiểm tra kiểu

#define typecheck(T) _Generic((T), \
    char: 1, \
    int: 2, \
    long: 3, \
    float: 4, \
    default: 0)

typecheck('a')   → 1 (char)
typecheck(123)   → 2 (int)
typecheck(123L)  → 3 (long)
typecheck(1.0f)  → 4 (float)
typecheck("str") → 0 (default - const char*)

Code C hoàn chỉnh

#include <stdio.h>

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

int main() {
    printf("long: %d\n", typecheck(2353463456356465L));
    printf("float: %d\n", typecheck(4.32f));
    printf("int: %d\n", typecheck(324));
    printf("double: %d\n", typecheck(3.14));
    printf("string: %d\n", typecheck("Hello"));
    return 0;
}

Kết quả

long: 3
float: 4
int: 2
double: 5
string: 0

Ứng dụng thực tế

// Macro in giá trị theo kiểu
#define print(x) _Generic((x), \
    int: printf("%d", x), \
    float: printf("%f", x), \
    double: printf("%lf", x), \
    char*: printf("%s", x), \
    default: printf("unknown") \
)(x)

Lưu ý

  • Yêu cầu trình biên dịch hỗ trợ C11 (-std=c11)
  • Chỉ hoạt động tại compile-time
  • Không thể dùng cho kiểu struct/union tùy chỉnh trừ khi liệt kê rõ