Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is iteration necessary in a 'continue if loop' in C++?

What I mean is this :

while (i < 10) {
    if (i == 4) {
        // i++; should be here, but if I skip it...
        continue;
    }
    cout << i << endl;
    i++;
}

I am getting this :

1
2
3
    

and that’s it! It just stays like that, without termination… unless I specifically mention i++ before continue in the if block, I have this "problem".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why do I have to specifically mention i++ ? Shouldn’t the continue statement just go to the next iteration ? Is this a feature and has no explanation, or is there something wrong with my code ?

Edit: Thanks to the comments for the answer! continue does indeed go to the next iteration, but since I did not increment it in the if block to change the outcome (from true to false) for the next time it goes through, the value of i stays 4 forever, thus becomes an infinite loop.

It is to be noted that it does not happen when using a for loop, because the syntax is different in the way that in a for loop, the i++ is given which doesn’t need to be mentioned specifically.

for (int i = 0; i < 10; i++) {
    if (i == 4) {continue;}
    cout << i << endl;
}

Here iteration is a part of the loop, hence I assume you wouldn’t run into the same problem when using a for loop.

>Solution :

Think about what the loop does:

It's 0! Lets print it and increment it. Lets go to the next iteration!
It's 1! Lets print it and increment it. Lets go to the next iteration!
It's 2! Lets print it and increment it. Lets go to the next iteration!
It's 3! Lets print it and increment it. Lets go to the next iteration!
It's 4! Lets continue to the next iteration!
It's 4! Lets continue to the next iteration!
It's 4! Lets continue to the next iteration!
It's 4! Lets continue to the next iteration!
... (and infinitely so)

You need to increase i for it to skip the "4"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading