Go to statement in C
Go to statement in C
What is the goto statement?
The goto statement is known as the jump statement in C. As the name suggests, the goto is used
to transfer the program control to a predefined label. The goto statement can
be used to repeat some part of the code for a particular condition. It can also
be used to break the multiple loops which can't be done by using a single break
statement. However, using goto is avoided these days since it makes the program
less readable and complicated.
The
go to statement is a jump statement which is sometimes also referred to as an unconditional jump statement. The goto statement can be used to jump from
anywhere to anywhere within a function.
Syntax
:-
2. Backward jump
Syntax1
| Syntax2
--------------------------
goto label;
| label:
. |
.
label: |
goto label;
Example:-
#include <stdio.h>
// function to check even or not
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump
to even
goto
even;
else
// jump
to odd
goto
odd;
even:
printf("%d is even", num);
// return if
even
return;
odd:
printf("%d is odd", num);
}
int main() {
int num =
26;
checkEvenOrNot(num);
return 0;
}
Type 2:- In this case, we will see a situation similar to as
shown in Syntax1 above.
The program explains
how to do this.
Example:-
// function to print numbers from 1 to 10
void printNumbers()
{
int n = 1;
label:
printf("%d ",n);
n++;
if (n <=
10)
goto
label;
}
//driver code
int main() {
printNumbers();
return 0;
}
Advantage:-
Drawbacks of using goto statement
1.The use of goto statement makes the program logic very complex.
2.use of goto makes the task of analyzing and verifying the correctness of programs very difficult.
3.Use of goto can be simply avoided using break and continue statements.

👍👍👍👍
ReplyDelete