C語言中##的用法以及##在變參的設計

C語言中##稱爲連接符,其功能是在帶參數的宏定義中將兩個子串(token)聯接起來,從而形成一個新的子串。
要注意下面的用法:
1、
[cpp]  
#include <stdio.h>  
#define debug(format, args...) fprintf(stderr, format, args)  
void main(void){  
        debug("Test \n");  
        return;  
}  
有的說這種情況下字符串後面會多一個逗號,但是我用gcc編譯不通過;
 
2、
[cpp] 
#include <stdio.h>  
#define debug(format, args...) fprintf(stderr, format, ##args)  
//#define debug(format, args...) fprintf(stderr, format, args)  
void main(void){  
        debug("Test \n");  
        return;  
}  
 
這樣可以編譯通過,執行正確;
 
3、
[cpp]  
#include <stdio.h>  
//#define debug(format, args...) fprintf(stderr, format, ##args)  
#define debug(format, args...) fprintf(stderr, format, args)  
void main(void){  
        debug("Test%d \n",1);  
        return;  
}  
 
這樣也正確;
 
#include<stdio.h>
#include<string.h>


#define stat_name(a,b)  a##b
#define debug(format,args...) fprintf(stdout,format,##args)
#define debug1(format,args) fprintf(stdout,format,args)
#define debug2(format,args...) fprintf(stdout,format,args)
int main(int argc, char** argv)
{
        debug1("%s\n","hello");
        debug("%s\n","hello");
        debug("test define\n");
        debug("%s,%d\n","this is age",10);
        debug2("this is %d\n",10);
        debug2("this is %s %d\n","this is",10);
        return 0;
}
hello
hello
test define
this is age,10
this is 10
this is this is 10

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章