เรารู้ว่าใน C สามารถใช้ Variable Length Arguments สำหรับฟังก์ชันได้ โดยใช้ Ellipsis (...) เช่นเดียวกัน Macro ก็สามารถรับอาร์กิวเมนต์จำนวนไม่คงที่ได้ โดยใช้ __VA_ARGS__ ในการจัดการ และออพอเรเตอร์ต่อสตริง ## สำหรับการต่ออาร์กิวเมนต์
ในตัวอย่างนี้ Macro จะรับอาร์กิวเมนต์แบบไม่คงที่คล้าย printf() หรือ scanf() โดยจะพิมพ์ชื่อไฟล์ หมายเลขบรรทัด และข้อความผิดพลาด อาร์กิวเมนต์แรกคือ pr ใช้ระบุความสำคัญ (Info หรือ Error)
ตัวอย่าง
#include <stdio.h>
#define INFO 1
#define ERR 2
#define STD_OUT stdout
#define STD_ERR stderr
#define LOG_MESSAGE(pr, strm, msg, ...) \
do { \
char *str; \
if (pr == INFO) \
str = "INFORMATION"; \
else if (pr == ERR) \
str = "ERROR"; \
fprintf(strm, "[%s] : %s : %d : " msg "\n", \
str, __FILE__, __LINE__, ##__VA_ARGS__); \
} while (0)
int main(void) {
char *s = "Test String";
LOG_MESSAGE(ERR, STD_ERR, "Unable to open the file");
LOG_MESSAGE(INFO, STD_OUT, "%s is passed as argument", s);
LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 14, 16, (14 + 16));
return 0;
}
ผลลัพธ์
[ERROR] : D:\text.c : 21 : Unable to open the file [INFORMATION] : D:\text.c : 23 : Test String is passed as argument [INFORMATION] : D:\text.c : 25 : 14 + 16 = 30