Suppose I have a piece of code like this:
int foo(int a, int b, int c)
{
int tmp1, tmp2, tmp3;
...
some_calculation0(&tmp1, a, b); // stores the result in tmp1
some_calculation1(&tmp2, b, c);
some_calculation2(&tmp3, tmp1, tmp2);
return tmp3;
}
Lately I would write this as:
int foo(int a, int b, int c)
{
int tmp[3];
...
some_calculation0(&tmp[0], a, b); // stores the result in tmp[0]
some_calculation1(&tmp[1], b, c);
some_calculation2(&tmp[2], tmp[0], tmp[1]);
return tmp[2];
}
Is there any reason not to do something like this? Would anyone consider it poor practice?
In this case the tmp values are really intermediate values in a string of computations, since all the functions return their result in one of the input variables passed by reference. To me it made sense to group them together, but seeing as the response so far has been against it, I have nothing against using separate variables.
This interferes with the readability of your code. Variable names should provide some information about their usage.
While using
tmpas a variable name is occasionally useful and reasonable, using an array of tmp in this way gives no indication about how the variables are being used: you’re hiding the details of your calculations behind an opaque name/structure. Furthermore I need to keep track of indices to figure out what’s going on in the code, which is confusing, and is prone to programmer error.It takes no more effort to pick specific variable names, and if the variables really have no better name than
tmpX, then prefer common conventions, for instance,x,y,zas iterators,indexoridxfor indices, etc..