Chrys Chrys - 3 months ago 16
C++ Question

C++ use `const int` as looping variable?

I want to write code that compiles conditionally and according to the following two cases:

CASE_A:

for(int i = 1; i <= 10; ++i){
// do something...
}


CASE_B: ( == !CASE_A)

{
const int i = 0;
// do something...
}


That is, in case A, I want to have a normal loop over variable
i
but, in case B, i want to restrict local scope variable
i
to only a special case (designated here as
i = 0
). Obviously, I could write something along the lines:

for(int i = (CASE_A ? 1 : 0); i <= (CASE_A ? 10 : 0); ++i){
// do something
}


However, I do not like this design as it doesn't allow me to take advantage of the
const
declaration in the special case B. Such declaration would presumably allow for lots of optimization as the body of this loop benefits greatly from a potential compile-time replacement of
i
by its constant value.

Looking forward to any tips from the community on how to efficiently achieve this.

Thank you!

EDITS:

CASE_A vs CASE_B can be evaluated at compile-time.

i
is not passed as reference

i
is not re-evaluated in the body (otherwise
const
would not make sense), but I am not sure the compiler will go through the effort to certify that

Answer

Assuming, you aren't over-simplifying your example, it shouldn't matter. Assuming CASE_A can be evaluated at compile-time, the code:

for( int i = 0; i <= 0; ++i ) {
    do_something_with( i );
}

is going to generate the same machine code as:

const int i = 0;
do_something_with( i );

for any decent compiler (with optimization turned on, of course).

In researching this, I find there is a fine point here. If i gets passed to a function via a pointer or reference, the compiler can't assume it doesn't change. This is true even if the pointer or reference is const! (Since the const can be cast away in the function.)