[C] Veriadic Functions

What if you need to pass multiple number of values to a function as parameters? The first choice is an array. But C provides another construct. You can pass a variable number of arguments to a function without creating an array. “printf()” is a good example.

 

1. Header Files

To create a veriadic functions, you need to include the “stdarg.h

#include <stdarg.h>

You need to make use of some types defined in the header file.

  • va_list : stores extra arguments
  • va_start(va_list, v) : specifies the starting point. “v” is the last known argument.
  • va_arg(va_list, type) : reads an argument one by one
  • va_end(va_list) : notifies you have finished

 

2. Declaring Veriadic Functions

Let’s create a function to add all integer values provided. As a first parameter, you will pass the number of extra arguments.

int Add_ints(int num, ...)
{
  int total = 0;

  va_list ap;
  va_start(ap, num);
  for(int i=0; i<num; i++)
  {
    total += va_arg(ap, int);
  }
  va_end(ap);

  return total;
}

 

3. Calling Veriadic Functions

It is easy to call veriadic functions. No special treatment here.

void PointerTest12()
{
  int sum = Add_ints(10, 1,2,3,4,5,6,7,8,9,10);
  printf("SUM 1:10 = %i n", sum);  /* 55 */
}

 

4. Example

Let’s have another example. This time we are saying Hello to many people.

void SayHello(char *greeting, int numPeople, ...)
{
  va_list ap;
  va_start(ap, numPeople);
  for(int i=0; i<numPeople; i++)
  {
    printf("%s, %s n", greeting, va_arg(ap, char *));
  }
  va_end(ap);
}

void PointerTest13()
{
  SayHello("Good morning", 3, "Homer", "Bart", "Lisa");
  printf("n");
  SayHello("Good night", 2, "Homer", "Bart");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s