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
C program to find sum, max and min with Variadic functions
Variadic functions in C allow you to create functions that can accept a variable number of arguments. This is useful when you need functions like sum(), max(), and min() that can work with different numbers of input values. To implement variadic functions, we use the ellipsis (...) notation and include the <stdarg.h> header file.
Syntax
return_type function_name(fixed_parameter, ...);
The key macros for handling variable arguments are −
- va_list: Stores information about variable arguments
- va_start: Initializes the va_list to start accessing arguments
- va_arg: Retrieves the next argument of specified type
- va_end: Cleans up the va_list when finished
Example: Sum, Max, and Min Functions
Here's a complete implementation of variadic functions to calculate sum, maximum, and minimum values −
#include <stdio.h>
#include <stdarg.h>
int sum(int cnt, ...) {
va_list ap;
int i, n = 0;
va_start(ap, cnt);
for (i = 0; i < cnt; i++) {
n += va_arg(ap, int);
}
va_end(ap);
return n;
}
int min(int cnt, ...) {
va_list ap;
int i, current, minimum;
va_start(ap, cnt);
minimum = va_arg(ap, int); // Initialize with first argument
for (i = 1; i < cnt; i++) {
current = va_arg(ap, int);
if (current < minimum) {
minimum = current;
}
}
va_end(ap);
return minimum;
}
int max(int cnt, ...) {
va_list ap;
int i, current, maximum;
va_start(ap, cnt);
maximum = va_arg(ap, int); // Initialize with first argument
for (i = 1; i < cnt; i++) {
current = va_arg(ap, int);
if (current > maximum) {
maximum = current;
}
}
va_end(ap);
return maximum;
}
int main() {
printf("Sum: %d
", sum(5, 5, 2, 8, 9, 3));
printf("Max: %d
", max(4, 5, 9, 2, 7));
printf("Min: %d
", min(6, 8, 5, 2, 6, 7, 9));
return 0;
}
Sum: 27 Max: 9 Min: 2
Key Points
- The first parameter (count) tells the function how many variable arguments to process
- For
min()andmax()functions, initialize with the first argument instead of hardcoded values - Always call
va_end()to clean up theva_list - Variable arguments are accessed in the same order they are passed
Conclusion
Variadic functions provide flexibility in C programming by allowing functions to accept variable numbers of arguments. They are essential for creating utility functions like mathematical operations that work with different input sizes.
