C 宏的變長引數
我們知道,我們可以在 C 中針對函式使用變長引數。為此,我們必須使用省略號 (…)。同樣,對於宏,我們也可以使用變長引數。在這裡,我們也必須包括省略號,使用 '__VA_ARGS__' 來處理變長引數。連線運算子 '##' 用於連線可變引數。
在此示例中,宏將獲取變長引數,例如 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"
", \
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP