宏定義中參數使用


1. 宏傳遞變長參數:

最近用C語言寫一個程序,經常調用shell或者其他命令,代碼中多處出現如下代碼:

char script_cmd[CMD_MAX_LEN + 1] = {'\0'};

memset(script_cmd, 0, sizeof(script_cmd));
sprintf(script_cmd, "cmd %s %s", param1, param2);
system(script_cmd);

 

每調用一次就是三行代碼,看着也十分不爽。偶然間學會通過宏傳遞參數,代碼瞬間簡化很多:

#define    EXECUTE_SCRIPT(script_cmd_array, format,args...) \
    memset(script_cmd_array, 0, sizeof(script_cmd_array)); \
    sprintf(script_cmd_array, format, ##args); \
    system(script_cmd_array);
    
char script_cmd[CMD_MAX_LEN + 1] = {'\0'};
EXECUTE_SCRIPT(script_cmd, "cmd %s %s", param1, param2);

 

2. 宏中參數當做字符串使用

 1 #define REMOVE_SHMEM(shmid) \
 2     if (shmid != -1) { \
 3         if (shmctl(shmid, IPC_RMID, NULL) == -1) { \
 4             printf("remove %s failed!\n", #shmid); \
 5         } \
 6     }
 7 
 8 int main (void)
 9 {
10     int myshm = 123;
11 
12     REMOVE_SHMEM(myshm);
13 }

輸出:

 remove myshm failed!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM