1

How can I implement a do-while loop only using goto statements?

do{
    // Some code
}
while ();

Like this, but only using goto to create the equivalent of that.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jbb
  • 217
  • 1
  • 7
  • 2
    This is currently being [discussed on Meta](//meta.stackoverflow.com/q/412681/5958455). – iBug Oct 30 '21 at 08:35
  • 3
    How is this not a duplicate? – Peter Mortensen Oct 30 '21 at 13:54
  • 1
    @PeterMortensen Good point. Probably the potential dupes were already all downvoted/closed/deleted or they are just difficult to find. – Bob__ Oct 30 '21 at 18:21
  • So why would you want to do this? Unlike Assembly, C will put the GOTO statements in your code through straightforward lexer and language rules. Adding GOTO statements to your code is a vehemently discouraged approach, and while there are some cases in which it's necessary, those are the exception more than the rule. – Makoto Oct 31 '21 at 22:50

2 Answers2

26
do{
    // Some code 
}
while (condition);

is equal to:

label:
{
     // Some code
}
if(condition) goto label;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0___________
  • 60,014
  • 4
  • 34
  • 74
2

A do-while loop is a variation of a while loop. The condition is checked by a while loop and statements are in the do segment.

The do while loop checks the condition at the end of the loop. This means that the statements inside the loop body will be executed at least once even if the condition is never true.

The variable within the scope of the loop. I.e. you need to be within the loop to access it. It's the same as if you declared a variable within a function, only things in the function have access to it.

do{
    statement(s);
}while(condition);

Instead of using a for, while, or do while loop, you can do the same job using goto. Like this:

int i = 0;

firstLoop:
    printf("%d", i);
    i++;
    if(i<10)
        goto firstLoop;
    printf("\nout of first loop");

But it is suggested not to use goto statements. The goal you achieve by using goto statement, can be achieved more easily using some other conditional statements like if-else, etc.

vegan_meat
  • 878
  • 4
  • 10