Looking for a neat way to pass many variables to a function

I have a function that initially looked like this:

double myfun(int var1, int var2, int var3, int var4, int var5, int var6);

I thought it might be easier just to pass a pointer to an array:

double myfun(int var_array []);

and then extract the values. However, once I'm in the function I want to give them their names back, as var_array[4] is much less descriptive than var5 (ok in this example it's not, but in my function they have meaningful names). However I also don't want to go creating a bunch of unecessary variables in my function:

1
2
3
4
5
6
7
8
double myfun(int var_array []) {
  int var1 = var_array[0];
  int var2 = var_array[1];
  int var3 = var_array[2];
  int var4 = var_array[3];
  
  // some code that uses var1, var2, etc.
};


Is my compiler (VC++ 2010) smart enough to know that it really doesn't need to actually create those variables, and can just inline their definitions? If not, can I somehow tell my compiler to do so, so that I can retain both the efficiency of the code as well as readability?
If these variables are all commonly grouped (which I assume they are, since you can put them in an array), a better solution would be to put them in a struct:

1
2
3
4
5
6
struct MyVars
{
  int var0;
  int var1;
  int var2;  // etc.  but give them meaningful names
};


Then you can just pass the struct around to different functions, rather than an array:

1
2
3
4
5
double myfun( const MyVars& vars )
{
  do_whatever_with( vars.var0 );  // etc
  //...
}



As for your actual question, if you want to go that way (which I don't recommend), a way to ensure a separate var is not created is to use references:

1
2
3
double myfun(int var_array []) {
  int& var1 = var_array[0]; // <- make it a reference
//... 


A reference effectively is just an alternative name for another variable.

But again -- I don't recommend this approach. Grouping common data in a struct or class is almost always the better way to go.
Topic archived. No new replies allowed.