Mysterious User
Mysterious User

Reputation: 57

How do I print function parameters in C?

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
}

Upvotes: 0

Views: 1467

Answers (1)

One Guy Hacking
One Guy Hacking

Reputation: 1291

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);
}

Upvotes: 1

Related Questions