?
Ce document utilise Manuel du site Web PHP chinois Libérer
變量函數(shù)是可以用不同數(shù)量的參數(shù)調(diào)用的函數(shù)。
只有新式(原型)函數(shù)聲明可能是可變的。這由...
必須出現(xiàn)在參數(shù)列表中的最后一個(gè)格式的參數(shù)表示,并且必須至少跟隨一個(gè)命名參數(shù)。
//New-style declarationint printx(const char* fmt, ...); // function declared this wayprintx("hello world"); // may be called with oneprintx("a=%d b=%d", a, b); // or more arguments // int printy(..., const char* fmt); // Error: ... must be the last// int printz(...); // Error: ... must follow at least one named parameter
在函數(shù)調(diào)用中,作為變量參數(shù)列表一部分的每個(gè)參數(shù)都會(huì)經(jīng)歷特殊的隱式轉(zhuǎn)換,稱為默認(rèn)參數(shù)促銷。
在使用可變參數(shù)的函數(shù)體內(nèi),可以使用<stdarg.h>庫(kù)函數(shù)來(lái)訪問(wèn)這些參數(shù)的值:
| Defined in header <stdarg.h> |
|:----|
| va_start | 允許訪問(wèn)可變參數(shù)函數(shù)參數(shù)(函數(shù)宏)|
| va_arg | 訪問(wèn)下一個(gè)可變參數(shù)函數(shù)參數(shù)(函數(shù)宏)|
| va_copy(C99)| 制作可變參數(shù)函數(shù)參數(shù)(函數(shù)宏)|的副本
| va_end | 結(jié)束可變參數(shù)函數(shù)參數(shù)(函數(shù)宏)|的遍歷
| va_list | 保存va_start,va_arg,va_end和va_copy(typedef)所需的信息|
雖然舊式(無(wú)原型)函數(shù)聲明允許后續(xù)函數(shù)調(diào)用使用任意數(shù)量的參數(shù),但它們不允許為可變參數(shù)(從C89開始)。這種函數(shù)的定義必須指定一個(gè)固定數(shù)量的參數(shù),并且不能使用這些stdarg.h
宏。
//old-style declarationint printx(); // function declared this wayprintx("hello world"); // may be called with oneprintx("a=%d b=%d", a, b); // or more arguments// the behavior of one of these calls is undefined, depending on// whether the function is defined to take 1 or 3 parameters
#include <stdio.h>#include <time.h>#include <stdarg.h> void tlog(const char* fmt,...){ char msg[50]; strftime(msg, sizeof msg, "%T", localtime(&(time_t){time(NULL)})); printf("[%s] ", msg); va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args);} int main(void){ tlog("logging %d %d %d...\n", 1, 2, 3);}
輸出:
[10:21:38] logging 1 2 3...
C11標(biāo)準(zhǔn)(ISO / IEC 9899:2011):
6.7.6.3/9函數(shù)聲明符(包括原型)(p:133)
7.16變量參數(shù)<stdarg.h>(p:269-272)
C99標(biāo)準(zhǔn)(ISO / IEC 9899:1999):
6.7.5.3/9函數(shù)聲明符(包括原型)(p:119)
7.15變量參數(shù)<stdarg.h>(p:249-252)
C89 / C90標(biāo)準(zhǔn)(ISO / IEC 9899:1990):
3.5.4.3/5函數(shù)聲明符(包括原型)
4.8變量<stdarg.h>