可變參數省略號使用簡介
C允許定義形參個數和類型不確定的函數。例如,C語言中的標准函數printf便使用這種機制。在聲明不確定形參的函數時,形參部分可以使用省略號“…”代替。“…”告訴編譯器,在函數調用時不檢查形參類型是否與實參類型相同,也不檢查參數個數。
如:
[root@centos-64-min exercise]# vi chang.c
#include <stdio.h>
int mult(int x , int y , const char * fmt , ...)
{
int result = x * y;
if(fmt)
{
printf("%s:" , fmt);
}
return result;
}
編譯器只檢查第一個參數,第二個參數是否為整數,檢查第三個參數是否是字符串,對後面的無論是什麼參數,有多少個參數全部歸入省略號處理,一律不管。
[root@centos-64-min exercise]# vi chang.c
#include <stdio.h>
int mult(int x , int y , const char * fmt , ...)
{
int result = x * y;
if(fmt)
{
printf("%s" , fmt);
}
return result;
}
int main(void)
{
int s = 0;
s = mult(1 , 2 , "1*2=");
printf("%d\n" , s);
s = mult(2 , 3 , "2*3=" , "hahaha" , 12345 , 66666); //完全忽視後面的參數“hahaha”、12345和66666
printf("%d\n" , s);
return 0;
}
"chang.c" 20L, 314C written
[root@centos-64-min exercise]# gcc -o chang chang.c
[root@centos-64-min exercise]# ./chang
1*2=2
2*3=6
可變參數在宏定義的使用
例子:
[root@centos-64-min exercise]# vi chang.c
s = rectangle_area(3 , 4 , "this rectangle's area is ");
#include <stdio.h>
int mult(int x , int y , const char * fmt , ...)
{
int result = x * y;
if(fmt)
{
printf("%s" , fmt);
}
return result;
}
#define rectangle_area(x , y , args...) mult(x , y , ##args)
#define square_area(x , args...) rectangle_area(x , x , ##args)
#define myprintf(args...) square_area(1 , ##args)
int main(void)
{
int s = 0;
s = rectangle_area(3 , 4 , "this rectangle's area is ");
printf("%d\n" , s);
s = rectangle_area(3 , 4 , "this rectangle's area is " , 1 , "hahaha");
printf("%d\n" , s);
s = square_area(3 , "this square's area is ");
printf("%d\n" , s);
s = square_area(3 , "this squre's area is " , "66666" , "hahaha" , 12345);
printf("%d\n" , s);
myprintf("6666666666666666666666666\n");
myprintf("hahahahahahahahahaha\n" , "66666666666666" , 12345);
return 0;
}
~
~
~
~
"chang.c" 34L, 819C written
[root@centos-64-min exercise]# gcc -o chang chang.c
[root@centos-64-min exercise]# ./chang
this rectangle's area is 12
this rectangle's area is 12
this square's area is 9
this squre's area is 9
6666666666666666666666666
hahahahahahahahahaha
簡單解析:
myprintf("hahahahahahahahahaha\n" , "66666666666666" , 12345);
相當於:
square_area(1 , "hahahahahahahahahaha\n" , "66666666666666" , 12345);
相當於:
rectangle_area(1 , 1 ,"hahahahahahahahahaha\n" , "66666666666666" , 12345);
相當於:
mult(1 , 1 ,"hahahahahahahahahaha\n" , "66666666666666" , 12345);
mult只讀取了mult(1 , 1 ,"hahahahahahahahahaha\n");
在這裡:各層define定義的##args的值都傳遞給args...,最頂層的##args <=> const char * fmt , ... 所以最終mult只讀取了args的第一個字符串的變量,後面的都是...處理了