#include <cstdarg>
#include <iostream>
//"severity" followed by a zero terminated list of char*s
void error(int severity ...) {
va_list ap;
va_start(ap, severity);
for (;;) {
char* p = va_arg(ap, char*);
if (p == nullptr) break;
std::cerr << p << ' ';
}
va_end(ap);
std::cerr << '\n';
if (severity) exit(severity);;
}
int main() {
error(0, "1", "2", "3");
return 0;
}
This is pretty much the same code except without for loop and its working perfectly.
Tnx for answer man, that really worked. But what if instead of char* I choose to use int p = va_arg(ap, int); and error(0, 1, 2, 3);
If 1st argument doesn't specify how many arguments there are, how can I write for loop without knowing how many arguments function caller supplied?
Is printf function just hopes that caller supplied correct number of arguments so that there would be one for each % sign?
Is printf function just hopes that caller supplied correct number of arguments so that there would be one for each % sign?
Yes.
If 1st argument doesn't specify how many arguments there are, how can I write for loop without knowing how many arguments function caller supplied?
That's one of the problems with C-style variadic functions. C++ has variadic templates that solve this problem in a better, more safe, way. Unfortunately it's somewhat more complicated for beginners.