From cppreference.com
Variadic functions are functions (e.g.
) which take a
.
To declare a variadic function, an ellipsis appears after the list of parameters, e.g. intprintf(constchar*format...);, which may be preceded by an optional comma. See
for additional detail on the syntax, automatic argument conversions and the alternatives.
To access the variadic arguments from the function body, the following library facilities are provided:
Defined in header
enables access to variadic function arguments
(function macro)
accesses the next variadic function argument
(function macro)
(C++11)
makes a copy of the variadic function arguments
(function macro)
ends traversal of the variadic function arguments
(function macro)
holds the information needed by
,
,
, and
(typedef)
Example
Run this code
#include<cstdarg>#include<iostream>voidsimple_printf(constchar*fmt...)// C-style "const char* fmt, ..." is also valid{va_listargs;va_start(args,fmt);while(*fmt!='\0'){if(*fmt=='d'){inti=va_arg(args,int);std::cout<<i<<'\n';}elseif(*fmt=='c'){// note automatic conversion to integral typeintc=va_arg(args,int);std::cout<<static_cast<char>(c)<<'\n';}elseif(*fmt=='f'){doubled=va_arg(args,double);std::cout<<d<<'\n';}++fmt;}va_end(args);}intmain(){simple_printf("dcff",3,'a',1.999,42.5);}Output:
3 a 1.999 42.5 See also