Reference arguments in ellipsis

closed account (DGvMDjzh)
Here's a simple function with an ellipsis in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void func(int n,...) {
 va_list list;
 va_start(list,n);

 int arg = va_arg(list,int); // what am I suppose to do here ._.
 arg = n + 7;

 va_end(list);
}

int main() {
 int result; 
 
 func(10,&result); 
 
 if (result == 17); // my goal 
}


I know it's possible because scanf() does it. But how?
your question is very vague, at least for me...
- you doesn't included the va_list definition
-
I know it's possible because scanf() does it
you don't include or ask about what scanf() going to do with your purpose...
¿What type is &result ?

Your example is awful

@chipp: look in stdarg.h the idea is to provide a function that can work with different number of parameters.
Last edited on
closed account (DGvMDjzh)
Sorry if my example is awful.

result is obviously an integer
I want to find a way to pass the value (n + 7) trough result via reference. But I have no idea how to do so.

I mentioned scanf because it has familiar functionality.

Example: scanf("%u",&result)

In scanf() an ellipsis arg can get altered which is what I want to do.
scnaf scans the format string and according to format specifiers extracts arguments.
Last edited on
closed account (D80DSL3A)
Here is an example. The sum() adds up a variable number of integer arguments and returns this sum.
It is a simple but complete example:
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
// variable number of function arguments

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

int sum(int 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);// argument type determined here. It can vary!
	
	va_end(arg_ptr);
	return sum;
}

int main(void)
{

	cout << sum(6, 2, 4, 6, 8, 10, 12) << endl;// 7 args. 1st gives # of args to follow
	cout << sum(9, 11, 22, 33, 44, 55, 66, 77, 88, 99) << endl;// 10 args
	
	cout << endl;
	return 0;	
}
@chipp: look in stdarg.h the idea is to provide a function that can work with different number of parameters.


thanks, now i learning something new...
closed account (DGvMDjzh)
@fun2code

This does not answer my question. I want to know how to extract the sum with one of the ellipses arguments.

Something along these lines:

1
2
int result;
sum(3, 4,6,&result) // result = 4 + 6  



In your example, you're passing the address of result, which is an int pointer.
Therefore when you extract it from the argument list, you have to extract it as an int pointer.

1
2
3
4
5
6
7
8
9
10
void func(int n,...) {
 va_list list;
 va_start(list,n);

 int * arg = va_arg(list,int *); 
*arg = n + 7;

 va_end(list);
}

closed account (DGvMDjzh)
Thank you! That's exactly what I was looking for :]
Topic archived. No new replies allowed.