Reputation: 33
Will C++ compilers automatically optimise the following code to calculate 3*i only once, and increment the result, or must the programmer code this?
void writeToArray(int i, int a, int b, int c)
{
array[3*i][1]=a;
array[3*i][2]=b;
array[3*i][3]=c;
}
Upvotes: 3
Views: 136
Reputation: 4780
With modern compilers you can most of the time rely on the compiler doing the clever job and not try anything yourself. See for instance http://dl.fefe.de/optimizer-isec.pdf
Upvotes: 3
Reputation: 146910
Common Subexpression Elimination is one of the easiest and most commonly applied optimizations. In general, you can rely on this being done.
Upvotes: 3
Reputation: 48775
Most optimizers will pick up on this, yes. However if you want to encourage the optimizer, here's how:
void writeToArray(int i, int a, int b, int c)
{
const int offset = 3 * i;
array[offset][1]=a;
array[offset][2]=b;
array[offset][3]=b;
}
Upvotes: 7
Reputation: 283624
When you enable optimization, almost all compilers will not only precompute the common index 3*i
but the pointer array + (3*i)*sizeof (*array)
.
Upvotes: 5