Home > other >  How to implement Do while loop only using GOTO in c language?
How to implement Do while loop only using GOTO in c language?

Time:10-30

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

CodePudding user response:

do{
// some code 
}
while (condition);

is equal to:

label:
{
 // some code
}
if(condition) goto label;

CodePudding user response:

Using jump statements upwards in C is considered very bad practice, also known as spaghetti programming. So the answer to your question is: there exists no valid use-case in C for goto upwards, you should never write such code. Period.

goto downwards may be acceptable in some special cases like error handlers.

CodePudding user response:

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

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

Instead of using for, while, 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.

CodePudding user response:

It is easy to do.

For starters you should take into account that the body of the do-while statement forms a block scope even if the body is not represented by a compound statement. For example this program is correct.

#include <stdio.h>

int main(void) 
{
    struct A
    {
        int s;
    };
    
    do
        printf( "sizeof( struct A { int x; int y; } )  = %zu\n", 
                sizeof( struct A { int x; int y; } ) );
    while ( sizeof( struct A ) == 8 );
    
    printf( "sizeof( struct A  )  = %zu\n", 
            sizeof( struct A ) );
    
    return 0;
}

The program output is

sizeof( struct A { int x; int y; } )  = 8
sizeof( struct A  )  = 4

That is the structure A declared in the sub-statement of the do-while statement is in its own inner scope relative to the scope where the do-while statement is written and where the structure A with one data member is defined. And each time when the sub-statement gets the control the structure A is declared anew.

The rewritten do-while statement using a goto statement will look the following way as it is shown in the demonstration program below. In this case you need to use a compound statement to introduce the inner scope.

#include <stdio.h>

int main(void) 
{
    struct A
    {
        int s;
    };
    
    L1:
    {
        printf( "sizeof( struct A { int x; int y; } )  = %zu\n", 
                sizeof( struct A { int x; int y; } ) );
    }
    
    if ( sizeof( struct A ) == 8 ) goto L1;
    
    printf( "sizeof( struct A  )  = %zu\n", 
            sizeof( struct A ) );
    
    return 0;
}
  • Related