4

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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
hqt
  • 29,632
  • 51
  • 171
  • 250
  • possible duplicate of [passing variable number of arguments](http://stackoverflow.com/questions/3836272/passing-variable-number-of-arguments) – Prof. Falken Jul 02 '12 at 08:00

4 Answers4

4

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

DPlusV
  • 13,706
  • 1
  • 19
  • 18
  • This is the correct answer. Just pay careful heed to the warning about the lack of type checking with variable arguments. – Ian Goldby Jul 02 '12 at 07:31
4

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.

Cygnus
  • 3,222
  • 9
  • 35
  • 65
3

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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
3
#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));
}
Trickfire
  • 443
  • 2
  • 5