va_list in function with empty parameter list

Sep 4, 2011 at 6:41pm
I want to declare / define a function like this:

void abc(...);

I don't need any fixed part in the parameter list, but what do i pass to va_start as second argument then?
Sep 4, 2011 at 7:08pm
va_start needs the address of the first argument to know where the rest of them lie in memory, which means that you need to include at least one parameter in the function.
Sep 4, 2011 at 7:18pm
Seems like i really have to include some dummy variable at the beginning of the parameter list.

Not a very nice solution, but it's working.

Thanks for your answer :)
Sep 5, 2011 at 3:23am
closed account (D80DSL3A)
Here's a sample program. The sum function returns the sum of the integer arguments supplied in the function call, except for the 1st argument, which = the number of arguments that follow it.
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
34
// variable number of function arguments

#include<iostream>
#include <cstdarg>
using namespace std;

int sum(int count, ...)// this function will add the values following count.
{
	if(count <= 0)
		return 0;

	va_list arg_ptr;
	va_start(arg_ptr, count);
	
	int sum = 0;
	for(int i=0; i<count; ++i)
		sum += va_arg(arg_ptr, int);
	
	va_end(arg_ptr);
	return sum;
}

int main(void)
{

                     // add the 6 numbers: 2+4+6+8+10+12 = 42
	cout << sum(6, 2, 4, 6, 8, 10, 12) << endl;// 7 args. 1st gives # of args to follow

                     // add the 9 numbers: 11+22+33+44+55+66+77+88+99 = 495
	cout << sum(9, 11, 22, 33, 44, 55, 66, 77, 88, 99) << endl;// 10 args
	
	cout << endl;
	return 0;	
}
Last edited on Sep 5, 2011 at 3:24am
Sep 5, 2011 at 10:06am
Not a very nice solution, but it's working.

I think that a nice solution would be to pass a vector(or another container depending on your purpose) to the function.
Topic archived. No new replies allowed.