Unspecified number of arguments C style

Hi, I'm having a little bit of trouble understanding the example in Stroustrup's book about this topic because its kind of not working.

This is basically the original code and it is not working.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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);


	char* x;
	x = va_arg(ap, char*);
	std::cout << x;

	x = va_arg(ap, char*);
	std::cout << x;

	x = va_arg(ap, char*);
	std::cout << x;
	
	
	va_end(ap);

	std::cerr << '\n';
	if (severity) exit(severity);;
}

int main() {

	error(0, "1", "2", "3");
        
        return 0;
}


Could anyone explain why the first code is not working?
You are not passing null to the function so it fails to detect the end of the argument list.

Try this instead.

 
error(0, "1", "2", "3", nullptr);
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?
Last edited on
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.

https://en.wikipedia.org/wiki/Variadic_template
Last edited on
Ok tnx a lot for nice info :) and happy New Year!
Topic archived. No new replies allowed.