Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Count Variable Numbers of Arguments in C?
In C programming, the ellipsis (...) allows functions to accept a variable number of arguments. To count these arguments, C provides three common approaches − passing the count as the first parameter, using NULL as a sentinel value, or parsing format specifiers like printf() does.
Syntax
#include <stdarg.h> return_type function_name(fixed_params, ...); va_list ap; va_start(ap, last_fixed_param); type value = va_arg(ap, type); va_end(ap);
Method 1: Using Count Parameter
The most straightforward approach is to pass the number of arguments as the first parameter −
#include <stdio.h>
#include <stdarg.h>
int get_sum(int count, ...) {
va_list ap;
int i;
int sum = 0;
va_start(ap, count);
for(i = 0; i < count; i++) {
sum += va_arg(ap, int);
}
va_end(ap);
return sum;
}
int main() {
printf("Sum of 5 numbers: %d<br>", get_sum(5, 8, 5, 3, 4, 6));
printf("Sum of 3 numbers: %d<br>", get_sum(3, 10, 20, 30));
return 0;
}
Sum of 5 numbers: 26 Sum of 3 numbers: 60
Method 2: Using NULL Sentinel
Another approach uses NULL (or -1 for integers) as the last argument to mark the end −
#include <stdio.h>
#include <stdarg.h>
int sum_until_zero(int first, ...) {
va_list ap;
int sum = first;
int value;
va_start(ap, first);
while((value = va_arg(ap, int)) != 0) {
sum += value;
}
va_end(ap);
return sum;
}
int main() {
printf("Sum until zero: %d<br>", sum_until_zero(5, 10, 15, 20, 0));
printf("Sum until zero: %d<br>", sum_until_zero(1, 2, 3, 0));
return 0;
}
Sum until zero: 50 Sum until zero: 6
Method 3: Format String Approach
Similar to printf(), this method counts format specifiers in a format string −
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
void print_integers(const char* format, ...) {
va_list ap;
int count = 0;
int i;
/* Count %d specifiers */
for(i = 0; format[i]; i++) {
if(format[i] == '%' && format[i+1] == 'd') {
count++;
i++; /* Skip the 'd' */
}
}
printf("Found %d integers: ", count);
va_start(ap, format);
for(i = 0; i < count; i++) {
printf("%d ", va_arg(ap, int));
}
va_end(ap);
printf("<br>");
}
int main() {
print_integers("%d %d %d", 10, 20, 30);
print_integers("%d %d", 100, 200);
return 0;
}
Found 3 integers: 10 20 30 Found 2 integers: 100 200
Key Points
- Always include <stdarg.h> header for variadic function support
- Use va_start() to initialize, va_arg() to access, and va_end() to clean up
- The count parameter method is most reliable and widely used
- Sentinel values work but require careful handling of the terminating value
Conclusion
Counting variable arguments in C requires a mechanism to determine when to stop processing. The count parameter approach is most common and reliable for this purpose.
