How do I implement arbitrary number of arguments in my Max(int num, ...) with ONLY arguments that needs to be compared in C? I'm using va_list from the C library stdarg.h
I've read Variable number of arguments in C programmng, but sadly it seems that there aren't any answers that can help me. Since it is a post in 2018, I wonder if there is a solution to my problem after 4 years from then.
I'm using va_list from the C library stdarg.h to implement Max() . While looking for the maximal value, I have to use for loop to retrieve the arguments from the very first to the last. And that is where I get stuck.
My goal is to implement Max() with only arguments that needs to be compared their value. But I can't find a way to stop my for loop from executing after it reach to the last argument. The mostly seem solutions on the net for breaking the for loop are:
- Adding an additional argument that represent the amount of arguments that you are passing in, which tells the for loop to loop for that amount of times
- Passing in a number that the for loop's condition part becomes
false-> break out of the loop (In my code below, I pass the argument-1in as the last argument to my function. When the for loop sees that value, it knows it has arrived to the end of the argument)
But the above solutions both require an additional arguments, which I can't achieve my goal. So are there any solutions that can help me with my problem? Any response is appreciated :)
#include <stdio.h>
#include <stdarg.h> // this library is required for infinite number of arguments
int Max(int num, ...){
va_list ap;
int temp;
va_start(ap,num);
int maximum = num;
for(temp = va_arg(ap,int); temp!= -1/*put condition here */; temp = va_arg(ap, int)){
if(temp > maximum){
maximum = temp;
}
}
va_end(ap);
return maximum;
}
int main(){
int maximum;
printf("the input vals are: 1 3 4 6 3 78 100\n");
maximum = Max(1,3,4,6,3,78,100, -1);
printf("maximum val: %d\n",maximum);
}
printfformat string, or use an end-of-list marker (like your-1).min()andmax()myself. To let my function available to access unfixed number of arguments, I find that there is something called variadic-function in C. This is when I find out that we always put an argument to show the end of the list, so I started to search if there are any solution that enable me to remove this additional argument which can make mymax()andmin()function looks prettier, and more straightforward to use. : )