0

I know this question has been asked many times but sorry, I couldn't find the answer. Below is a function with parameters (how many parameters is unknown). How do I get all parameters and then print them?

int func(int a, int b, ...) {
  // print the parameters
}
  • 3
    Possible duplicate of [An example of use of varargs in C](https://stackoverflow.com/questions/15784729/an-example-of-use-of-varargs-in-c) – that other guy Jul 09 '18 at 22:31
  • That's something C won't help you with. It's not a very reflexive language. Almost not at all reflexive one might say. – Petr Skocik Jul 09 '18 at 22:32
  • 3
    Unless `a` or `b` tells you how many arguments were actually passed (and you know their types), you can't do this in C. When writing the code, you have to know, by some combination of the fixed arguments passed, and any other knowledge you may have, how many arguments there will be and what types they have. (For example, `printf` does this by parsing its format string.) There's no general way to empirically determine this at run time. – Steve Summit Jul 09 '18 at 22:38
  • @SteveSummit Please submit that as an answer. :) –  Jul 09 '18 at 22:46
  • take a look at http://www.cplusplus.com/reference/cstdarg/ – ergesto Jul 09 '18 at 22:56

1 Answers1

1

The short answer is "you don't." C doesn't give you any mechanism to know when the arguments end.

If you want to use varargs, you will need to give yourself a mechanism that will tell you how many arguments there are, and how big each one is. To take the most well-known example, printf() requires its first argument to be a formatting string, that tells it about the varargs and their sizes.

If you know that all your arguments are going to be the same size (say, ints), you can design your routine so the first argument is the number of arguments, something like:

void
my_func (int n_args, ...)
{
    va_list ap;
    int i;

    va_start(ap, n_args);
    for (i = 0 ; i < n_args ; i++) {
        process(va_arg(ap, int));
    }
    va_end(ap);
}
One Guy Hacking
  • 1,176
  • 11
  • 16