Reputation: 30266
When learning C I see that printf
can receive many arguments as it is passed.
And I don't know how C can implement a function like this, where the user can type as many parameters as the user wants. I have thought about pointers, too but still have no bright idea. If anyone has any ideas about this type of function, please tell me.
Upvotes: 4
Views: 228
Reputation: 59607
You use C varargs
to write a variadic function. You'll need to include stdargs.h
, which gives you macros for iterating over an argument list of unknown size: va_start
, va_arg
, and va_end
, using a datatype: va_list
.
Here's a mostly useless function that prints out it's variable length argument list:
void printArgs(const char *arg1, ...)
{
va_list args;
char *str;
if (arg1) We
va_start(args, arg1);
printf("%s ", arg1);
while ((str = va_arg(argp, char *)) != NULL)
printf("%s ", str);
va_end(args);
}
}
...
printArgs("print", "any", "number", "of", "arguments");
Here's a more interesting example that demonstrates that you can iterate over the argument list more than once.
Note that there are type safety issues using this feature; the wiki article addresses some of this.
Upvotes: 3
Reputation: 443
#include <stdarg.h>
#include <stdio.h>
int add_all(int num,...)
{
va_list args;
int sum = 0;
va_start(args,num);
int x = 0;
for(x = 0; x < num;x++)
sum += va_arg(args,int);
va_end(args);
return sum;
}
int main()
{
printf("Added 2 + 5 + 3: %d\n",add_all(3,2,5,3));
}
Upvotes: 3
Reputation: 3330
You need to use va_args, va_list and the like. Have a look at this tutorial. http://www.cprogramming.com/tutorial/c/lesson17.html
That should be helpful.
Upvotes: 4
Reputation: 14326
You have to use the ...
notation in your function declaration as the last argument.
Please see this tutorial to learn more: http://www.cprogramming.com/tutorial/c/lesson17.html
Upvotes: 4