Tag: goto

New tutorial on C loop statements published

New tutorial on C loop statements published

Mandala loops
Image by Renate Anna Becker from Pixabay

There are four types of loop statements in C, for loops, while loops, do-while loops and goto statements. The first two are much more popular; In my Windows asteroids game, I used 54 for-loops, six while-loops, three do-while loops and no gotos.

I found the same thing in Delphi and Turbo Pascal. The only difference is that Pascal uses repeat .. until instead of do-while and I prefer repeat-until.  The logic is slightly clearer I feel as well. You repeat the body of the loop until a condition becomes true. In the C do-while statement, you repeat the body of the loop as long as the condition is true.

Anyway I’ve published tutorial eleven on C loop statements. Have fun. I’ll get it added to the tutorials page shortly..

Goto is considered bad programming in C but

Goto is considered bad programming in C but

goto exit signThere is one case for using goto when you have nested loops and you’d like to jump all the way out. The goto statement was very popular in BASIC but often resulted in programs being like spaghetti with gotos all over the place.

Here’s a contrived example where I have used a goto.

#include <stdio.h> 

int array[10][10][10];
int main() {
    // Populate array
    for (int y=0;y<10;y++)
      for (int x=0;x<10;x++) 
        for (int z=0;z<10;z++) {
          if (array[x][y][z]==0)
            goto exit;
    }
exit:;
}

In my C programs, for-loops are the most popular followed by while-loops, do-while loops and gotos are hardly ever used at all.