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:
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;
}
CodePudding user response:
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.
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.