Home  >  Article  >  Backend Development  >  How to count variable number of arguments in C?

How to count variable number of arguments in C?

王林
王林forward
2023-09-18 15:37:021303browse

How to count variable number of arguments in C?

In this section, we will see how to calculate the number of arguments when the number of arguments is variable in C.

C supports ellipses. This is used to pass a variable number of arguments to a function. The user can count parameters in one of three different ways.

  • Pass the first argument as the argument count

  • Pass the last argument as NULL.

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

In the following program we will total The number of parameter variables passed.

Sample code

#include<stdio.h>
#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));
}

Output

Total variable count is: 5

The above is the detailed content of How to count variable number of arguments in C?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete