Go to specific element C


April 2019


58 time


I want to use a for loop to iterate through vector and when a certain condition is met, I want to go back to a certain element of vector and restart the loop from there.

For example, let's say that my vector is 1,2,3,4,5,6,7,8,9; and when the first element that is bigger than 5 is met, I want to restart the loop from number 3 again.

This is just an example.

I don't know if I can write something like:

for(int i = 0; i < 8; i ++)
   if(v[i] > 5)
      i = 3;

Is this correct? If no, how can I do this using a for loop and the index of the vector?


1 answers


Yes, it is perfectly fine to assign a value of choice to a loop variable inside the loop and its behaviour is well defined.

You just have to realise that if this process leads to an infinite loop, you should put a check in place to be able to break out of the loop.