Passing an array of variables by reference

Hi,

I define an integer variable and pass it by reference to a function.
1
2
3
4
5
6
7
int func(int &x)
{
// do something
}

int x;
func(x);


However, I have not only one variable but an array of variables with its predefined name. How do I pass to the function by using loop? Example:
1
2
3
4
int x, y, z;
func(x);
func(y);
func(z);

How can I do this by using loop? Any suggestion?
Thanks.
Last edited on
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
// http://ideone.com/KX3ciT
#include <iostream>

void double_it(int& val)
{
    val *= 2;
}

void print_it(int val)
{
    std::cout << val << '\n';
}

int main()
{
    int values[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    for (auto value : values)
        print_it(value);
    std::cout << '\n';

    for (auto& value : values)
        double_it(value);

    for (auto value : values)
        print_it(value);
    std::cout << '\n';
}
1
2
3
4
5
6
7
8
9
10

2
4
6
8
10
12
14
16
18
20
Thanks for quick reply. I understood this. But my question was something different. Rather than puting value in the array values[], I want to put variable names. I am having problem because variable names are pre-defined. I want to doe something like this:
 
int values[] = {x, y, z};

where x,y and z are just variable name.

Let look it another way. I have a lots of variables already defined such are
 
int a, b, c, d, ........., x, y, z;

Now, I want to pass these variables by reference, like this:
1
2
3
4
5
6
int func(int &x)
{
return x++;
}

cout << func(x) << endl;


For few variable, I can call this function for each variable separately, but if there are a lots then I want to use loop. How can I use loop?
Last edited on
Why do you have a lot of variables that you need to loop through? That's a sign of poor design.

If you have to, you can use a variadic template function, but I recommend rethinking your design first.
Actually, I am using external library which requires to pass variable by reference and there are many variables that need to pass.
Unless you go into more details, the current answer to your question is "no".
1
2
3
4
int *vars[3] {&x, &y, &z};
for (int i=0; i<3; ++i) {
   func(vars[i]);
}
dhayden, thanks it works.
Topic archived. No new replies allowed.