The problem with "arbitrary number of arguments" is how do you know how many there are.
The std::min
and std::min_element
work around this by working on containers - in other words, we know how many thanks to the container object itself knows how many.
In plain C, you can't really do that. So there needs to be some other method.
One way would be to use <cstdarg>
, and either mark the end with a special value:
#include <iostream>
#include <cstdarg>
using namespace std;
int countargs(int arg, ...)
{
if (arg == -1)
return 0;
int count = 1; // arg is not -1, so we have at least one arg.
va_list vl;
int cur;
va_start(vl, arg);
for(;;)
{
cur = va_arg(vl, int);
if(cur == -1)
break;
count++;
}
va_end(vl);
return count;
}
int main()
{
cout << "Should give 0: " << countargs(-1) << endl;
cout << "Should give 1: " << countargs(1, -1) << endl;
cout << "Should give 3: " << countargs(1, 2, 3, -1) << endl;
cout << "Should give 6: " << countargs(1, 2, 3, 1, 2, 3, -1) << endl;
cout << "Should give 12: " << countargs(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, -1) << endl;
return 0;
}
The above doesn't show how to get the min
value, but it shouldn't be that hard to figure out. It's also C++, but doesn't rly on any special C++ features.
The alternative to "marking the end" is to pass the number of elements to the function itself.
Of course, if the arguments are in an array, the real solution is to just iterate through them. And if there aren't that many, you can of course use:
v = min(a, min(b, min(c, d)));;