How to Count Variable Numbers of Arguments in C?
C supports variable numbers of arguments. But there is no language provided way for finding out total number of arguments passed. User has to handle this in one of the following ways:
1) By passing first argument as count of arguments.
2) By passing last argument as NULL (or 0).
3) Using some printf (or scanf) like mechanism where first argument has placeholders for rest of the arguments.
Following is an example that uses first argument arg_count to hold count of other arguments.
#include <stdarg.h> #include <stdio.h> // this function returns minimum of integer numbers passed. First // argument is count of numbers. int min( int arg_count, ...) { int i; int min, a; // va_list is a type to hold information about variable arguments va_list ap; // va_start must be called before accessing variable argument list va_start (ap, arg_count); // Now arguments can be accessed one by one using va_arg macro // Initialize min as first argument in list min = va_arg (ap, int ); // traverse rest of the arguments to find out minimum for (i = 2; i <= arg_count; i++) { if ((a = va_arg (ap, int )) < min) min = a; } //va_end should be executed before the function returns whenever // va_start has been previously used in that function va_end (ap); return min; } int main() { int count = 5; // Find minimum of 5 numbers: (12, 67, 6, 7, 100) printf ( "Minimum value is %d" , min(count, 12, 67, 6, 7, 100)); getchar (); return 0; } |
chevron_right
filter_none
Output:
Minimum value is 6
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Variable length arguments for Macros
- Why variable name does not start with numbers in C ?
- Can we access global variable if there is a local variable with same name?
- Internal static variable vs. External static variable with Examples in C
- Command line arguments in C/C++
- Command line arguments example in C
- Templates and Default Arguments
- When do we pass arguments by reference or pointer?
- Some Interesting facts about default arguments in C++
- Default arguments and virtual function
- C++ | Function Overloading and Default Arguments | Question 5
- C++ | Function Overloading and Default Arguments | Question 4
- C++ | Function Overloading and Default Arguments | Question 3
- C++ | Function Overloading and Default Arguments | Question 2
- C++ | Function Overloading and Default Arguments | Question 5