I get by in programming via experimentation and google. However, there are times where I wish I knew how to program more ‘proper’. I’ve been wanting to learn how to make iphone apps for some time now so thanks to davey I’ve been watching a few tutorial videos on objective-c. Many start with the basics which can be quite tedious, but I suffer through them to make sure I don’t miss any crucial information. Today I learned exactly what break & continue mean in the context of a for loop. I had an idea previously but never bothered to look up the formal definition. So lets for instance look at this for loop:

for (int i = 1; i < 5000; i++){
    if (i == 101)
    break;
    printf("The index value is %i\n",i);
}
This loop is super simple: it prints the value of i until i==101 when it completely drops out of the loop. On the other hand we have:
for (int i = 1; i < 5000; i++){
    if (i % 5. == 0)
    continue;
    printf("The index value is %i\n",i);
}

which says that if the remainder of i/5 is equal to 0, then consider this specific loop iteration finished and move on to the next one without executing any of the code below. The % sign here is known as the modulus operator.

In summary:

break;    //DROPS OUT OF THE FOR LOOP COMPLETELY
continue; //COMPLETES CURRENT ITERATION AND MOVES ON TO THE NEXT

Comments

comments powered by Disqus