Anıl Erturk Anıl Erturk - 10 months ago 46
C Question

Calculation of values of header expressions of for structure in C

I have been working on euler project lately and i thought i might aswell solve these problems modularly so i can add the functions to my personal library. When i made the code modular i have seen some expressions that might be inefficient.

for( ; forCounter <= limit / number1 * number1; forCounter += number1)

for( ; forCounter <= limit / number2 * number2; forCounter += number2)

for( ; forCounter <= limit / (number1 * number2) * (number1 * number2); forCounter += number1 * number2)

Are these calculations done only one time or every single iteration? A close example to this would be the expression "int x = 5" in a loop. First time it gets declared and initialized but in other iterations it is just assigned the value.

Answer Source

yes, this is very inefficient because these calculations done on every single iteration (some time compiler can optimize code, if view that limit , number1 and number2 is unchanged during loop time). but general rule - need calculate all constant (during loop time) expressions before loop but not every time in loop. so code must be like this:

ULONG n = limit / number1 * number1;
for( ; forCounter <= n; forCounter += number1) { ...}

ULONG m = number1 * number2, n  = limit / m * m;
for( ; forCounter <= n; forCounter += m) { ... }