How to Count Variable Numbers of Arguments in C?

CServer Side ProgrammingProgramming

In this section we will see how to count number of arguments in case of variable number of arguments in C.

The C supports ellipsis. This is used to take variable number of arguments to a function. User can count the arguments by using one of the three different ways.

  • By passing the first argument as count of the parameters

  • By passing last argument as NULL.

  • Using the logic like printf() or scanf() where the first argument has the placeholders for other arguments.

In the following program, we will total number of variable of arguments passed.

Example Code

#include <stdarg.h>
int get_avg(int count, ...) {
   va_list ap;
   int i;
   int sum = 0;
   va_start(ap, count); //va_start used to start before accessing arguments
   for(i = 0; i < count; i++) {
      sum += va_arg(ap, int);
   va_end(ap); //va_end used after completing access of arguments
   return sum;
main() {
   printf("Total variable count is: %f", get_avg(5, 8, 5, 3, 4, 6));


Total variable count is: 5
Updated on 30-Jul-2019 22:30:25