what is the argument list in the printf() function? [duplicate]
Possible Duplicate:
What is the signature of printf?
I know that 开发者_如何学JAVAthere will be an argument list for every function. if we pass the arguments more than no.of variables mentioned in the argument list then it gives an error.but my question is
Printf() function also has argument list and eventhough we give 'n' no.of arguments the printf() function doesnt fails then
i want to know wht will be used in argument list section of printf() which takes infinate argument list?
printf is a "variadic" function. This means that the argument list is declared with ...
on the end, and in the implementation of printf the va_list
, va_start
, va_arg
etc macros are used to extract the arguments from the variable length list.
printf's signature looks something like this:
int printf ( const char * format, ... );
If a function has a '...' as its last argument, it can receive any number of arguments. Within the function, you would use va_arg to access those arguments. Here is an example from cplusplus.com:
/* va_start example */
#include <stdio.h>
#include <stdarg.h>
void PrintFloats ( int amount, ...)
{
int i;
double val;
printf ("Floats passed: ");
va_list vl;
va_start(vl,amount);
for (i=0;i<amount;i++)
{
val=va_arg(vl,double);
printf ("\t%.2f",val);
}
va_end(vl);
printf ("\n");
}
int main ()
{
PrintFloats (3,3.14159,2.71828,1.41421);
return 0;
}
Notice that PrintFloats here requires that you pass in the number of additional arguments. printf doesn't need to do this, because it can infer how many arguments you are passing in by counting the tags in the format string.
The keyword is variadic arguments, and they are declared with ...
精彩评论