dynamic parameter function

Hello @all
Suppose I have a function

1
2
3
4
5
struct s_input{
  ...
};
  s_input in;
  void test(s_input *a, ...);


I have a variable "num" (parameter of constructor)

if num = 1 -> test(&in);
if num = 2 -> test(&in, &in);
if num = 3 -> test(&in, &in, &in);
if num = 4 -> test(&in, &in, &in, &in);
bla...bla...
How I can set dynamic parameter for test() depend on num?
the easy way is to pass in a vector of s_inputs.
is there some reason you want to make this more aggravating than by doing that? You can, if you have a good reason to do so.

vector<s_input> in(num);
for(auto &a:in)
{
//populate in data
a.data = something;
}

...
test(vector<s_input> &vs)
{
///you can use vs.size for num, or a ranged for loop again as above example, ...
// do something with each one..
}
Last edited on
Hello @jonnin, @coder777, @George P

I meant suppose I cannot update test function, I only use it.
Imagine it as the printf function in C,
How I can set dynamic parameter for printf() depend on num?
if num = 1 -> printf("%d",num);
if num = 2 -> printf("%d %d",num, num);
if num = 3 -> printf("%d %d %d",num, num, num);
if num = 4 -> printf("%d %d %d %d",num, num, num, num);
...
Thank you!
for ( int i = 0; i < num; i++ ) cout << num << ' ';

TBH, you haven't given enough context to understand what you want.
Last edited on
Do you ask how to do this:
1
2
3
4
5
6
7
8
9
if ( num == 1) {
  printf("%d", num);
} else if ( num == 2 ) {
  printf("%d %d", num, num);
} else if ( num == 3 ) {
  printf("%d %d %d", num, num, num);
} else if ( num == 4 ) {
  printf("%d %d %d %d", num, num, num, num);
}
hmm. all I can think of without going macro on it (eww) is this sort of thing:
char cs[1000]{};
char tmp[100]{};
for(int i = 0; i < num; i++)
{
sprintf(tmp, "%d ", num);
strcat (cs, tmp);
}
Last edited on
I think jonnin's suggestion will work for purposes of printing (you will print the cs string after the for loop). But just for reference, the terms you're looking for are "variadic functions" or "varargs" for a dynamic number of arguments to a function.
Topic archived. No new replies allowed.