Home > Backend Development > C++ > body text

How to count variable number of arguments in C?

王林
Release: 2023-09-18 15:37:02
forward
1297 people have browsed it

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));
}
Copy after login

Output

Total variable count is: 5
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!