Yes, C has the concept of variadic functions, which is similar to the way printf()
allows a variable number of arguments.
A maximum function would look something like this:
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
static int myMax (int quant, ...) {
va_list vlst;
int i;
int num;
int max = INT_MIN;
va_start (vlst, quant);
for (i = 0; i < quant; i++) {
if (i == 0) {
max = va_arg (vlst, int);
} else {
num = va_arg (vlst, int);
if (num > max) {
max = num;
}
}
}
va_end (vlst);
return max;
}
int main (void) {
printf ("Maximum is %d\n", myMax (5, 97, 5, 22, 5, 6));
printf ("Maximum is %d\n", myMax (0));
return 0;
}
This outputs:
Maximum is 97
Maximum is -2147483648
Note the use of the quant
variable. There are generally two ways to indicate the end of your arguments, either a count up front (the 5
) or a sentinel value at the back.
An example of the latter would be a list of pointers, passing NULL
as the last. Since this max
function needs to be able to handle the entire range of integers, a sentinel solution is not viable.
The printf
function uses the former approach but slightly differently. It doesn't have a specific count, rather it uses the %
fields in the format string to figure out the other arguments.