Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It Ever Good Practice To Modify The Index Variable Inside a FOR Loop?

Tags:

c#

Given the code:

for (int i = 1; i <= 5; i++)
        {
            // Do work
        }

Is is ever acceptable to change the value of i from within the loop? For example:

for (int i = 1; i <= 5; i++)
        {
            if( i == 2)
            {
               i = 4;
            }
            // Do work
        }
like image 715
DaveB Avatar asked Feb 14 '11 19:02

DaveB


People also ask

Can you change i in a for loop?

If you put i = 4 then you change i within the step of the current iteration. After the second iteration it goes on as expected with 3. If you wnat a different behaviour don't use range instead use a while loop. If you are using a for loop, you probably shouldn't change the index in multiple places like that.

What is a for loop index variable?

The loop variable defines the loop index value for each iteration. You set it in the first line of a parfor statement. parfor p=1:12. For values across all iterations, the loop variable must evaluate to ascending consecutive integers. Each iteration is independent of all others, and each has its own loop index value.

Can we use a double value as in index in a for loop?

Yes, it is, there is no restriction about it. In C++ is also very common creating for loops with iterators. Show activity on this post. This is legal in C and C++ but might not have the behavior you expect unless you understand floating-point and use it properly.


2 Answers

In my opinion, it is too confusing. Better use a while loop in such case.

like image 76
Petar Minchev Avatar answered Oct 17 '22 01:10

Petar Minchev


It is acceptable, however, I personally think this should be avoided. Since it's creating code that will be unexpected by most developers, I find that it's causing something much less maintainable.

Personally, if you need to do this, I would recommend switching to a while loop:

int i=1;
while (i <= 5)
{
    if (i == 2)
        i = 4;

    ++i;
}

This, at least, warns people that you're using non-standard logic.

Alternatively, if you're just trying to skip elements, use continue:

for (int i = 1; i <= 5; i++)
{
    if (i == 2 || i == 3)
       continue;
}

While this is, technically, a few more operations than just setting i directly, it will make more sense to other developers...

like image 6
Reed Copsey Avatar answered Oct 17 '22 02:10

Reed Copsey