Will an operation done several times in sequence be simplified by compiler?

As a matter of course, you should remove the obfuscation present in your code:

for (int i = 0; i < 100; ++i) {
    int i30 = i % 3 * 10;
    int r = someFunction(i30);
    array[i30] = r;
    anotherFunction(-r);
}

Suddenly, it looks quite a lot simpler.

Leave it to the compiler (with appropriate options) to optimize your code unless you find you actually have to take a hand after measuring.
In this case, unrolling three times looks like a good idea for the compiler to pursue. Though inlining might always reveal even better options.


Which optimizations are done depends on the compiler, the compiler optimization flag(s) you specify, and the architecture.

Here are a few possible optimizations for your example:

  • Loop Unrolling This makes the binary larger and thus is a trade-off; for example you may not want this on a tiny microprocessor with very little memory.
  • Common Subexpression Elimination (CSE) you can be pretty sure that your (i % 3) * 10 will only be executed once per loop iteration.

About your concern about visual clarity vs. optimization: When dealing with a 'local situation' like yours, you should focus on code clarity.

Optimization gains are often to be made at a higher level; for example in the algorithm you use.

There's a lot to be said about optimization; the above are just a few opening remarks. It's great that you're interested in how things work, because this is important for a good (C/C++) programmer.