Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What are variadic arguments in C?

Khizar Hayat Saani

Variadic arguments is the term used to refer to the arguments of a variadic function.

Variadic functions

A variadic function is one that takes a variable number of arguments. A common example is the printf() function defined in the <stdio.h> header.

The declaration of a variadic function uses ellipses as the last parameter.

The prototype for the printf() function is as follows:

int printf(const char* format, ...);
Two examples for the printf() variadic function

Accessing variadic arguments

To access variadic arguments, we must include the <stdarg.h> header.

We use the following library facilities:

Facilities defined in <stdarg.h>

Facility

Use

va_start

start access to variadic arguments

va_arg

access the next variadic argument

va_copy

makes a copy of the variadic arguments

va_end

end traversal of variadic arguments

va_list

holds information needed by other facilities

Code

#include <stdio.h>
#include <stdarg.h>

int variadic_addition (int count,...)
{
  va_list args;
  int i, sum;

  va_start (args, count);         /* Save arguments in list. */

  sum = 0;
  for (i = 0; i < count; i++)
    sum += va_arg (args, int);    /* Get the next argument value. */

  va_end (args);                  /* Stop traversal. */
  return sum;
}


int main(){

  // call 1: 4 arguments
  printf("Sum: %d\n", variadic_addition(3, 10, 20, 30));

  //call 2: 6 arguments
  printf("Sum: %d\n", variadic_addition(5, 10, 20, 30, 40, 50));

  return 0;

}

variadic_addition() adds all the variadic arguments and returns the sum.

This function is able to process both calls that were made, each with a different number of arguments.

RELATED TAGS

c

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring