เรารู้ว่าเราสามารถใช้อาร์กิวเมนต์ความยาวผันแปรสำหรับฟังก์ชันใน C ได้ เพื่อที่เราจะต้องใช้จุดไข่ปลา (…) ในทำนองเดียวกันสำหรับมาโคร เราสามารถใช้อาร์กิวเมนต์ความยาวผันแปรได้ ที่นี่เราต้องรวมจุดไข่ปลาด้วย '__VA_ARGS__' ใช้เพื่อจัดการอาร์กิวเมนต์ความยาวผันแปร โอเปอเรเตอร์การต่อ '##' ใช้เพื่อเชื่อมอาร์กิวเมนต์ของตัวแปร
ในตัวอย่างนี้ Macro จะใช้อาร์กิวเมนต์ความยาวผันแปรได้ เช่น ฟังก์ชัน printf() หรือ scanf() ในมาโครนี้ เราจะพิมพ์ชื่อไฟล์ หมายเลขบรรทัด และข้อความแสดงข้อผิดพลาด อาร์กิวเมนต์แรกคือ pr ใช้เพื่อกำหนดลำดับความสำคัญ เช่น สตริงข้อมูลปกติหรือข้อผิดพลาด
ตัวอย่าง
#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"); //here normal message will be printed LOG_MESSAGE(INFO, STD_OUT, "%s is passed as argument", s); //pass string argument LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 14, 16, (14 + 16)); //Provide integer }
ผลลัพธ์
[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