_คำหลักทั่วไปในภาษา C ใช้เพื่อกำหนด MACRO สำหรับประเภทข้อมูลต่างๆ คีย์เวิร์ดใหม่นี้ถูกเพิ่มลงในภาษาการเขียนโปรแกรม C ในรุ่นมาตรฐาน C11 คีย์เวิร์ด _Generic ถูกใช้เพื่อช่วยให้โปรแกรมเมอร์ใช้ MACRO ได้อย่างมีประสิทธิภาพมากขึ้น
คีย์เวิร์ดนี้แปล MACRO ตามประเภทของตัวแปร มาดูตัวอย่างกัน ,
#define dec(x) _Generic((x), long double : decl, \ default : Inc , \ float: incf )(x)
ไวยากรณ์ข้างต้นเป็นวิธีการประกาศ MACRO เป็นแบบทั่วไปสำหรับวิธีการต่างๆ
มาดูตัวอย่างโค้ดกัน รหัสนี้จะกำหนด MACRO ที่จะคืนค่าตามประเภทข้อมูล -
ตัวอย่าง
#include <stdio.h>
#define typecheck(T) _Generic( (T), char: 1, int: 2, long: 3, float: 4, default: 0)
int main(void) {
printf( "passing a long value to the macro, result is %d \n", typecheck(2353463456356465));
printf( "passing a float value to the macro, result is %d \n", typecheck(4.32f));
printf( "passing a int value to the macro, result is %d \n", typecheck(324));
printf( "passing a string value to the macro, result is %d \n", typecheck("Hello"));
return 0;
} ผลลัพธ์
passing a long value to the macro, result is 3 passing a float value to the macro, result is 4 passing a int value to the macro, result is 2 passing a string value to the macro, result is 0