c goto statement

c goto statement

The goto statement is unconditional control statement that transfers the cursor of current to the another part of the program. goto statement can be used as—

goto;

goto label;
………
………
………
label:
statement
……..
……..
……..

label is any valid identifier and it is followed by semicolon. whenever the goto label is encounter then control is transfer to the define label, that is immediately after the label.

.

/* program to find the number is even or odd using goto statement*/
#include<stdio.h>
int
main()
{
int num;
printf("Enter a number to check even or odd");
scanf("%d",&num);
if(num%2==0)
{
goto even;
}
else
{
goto odd;
}
even:
printf("Number is even \n");
goto end;
odd:
printf("Number is ODD \n");
goto end;
end:
printf("\n");
return 0;
}

Enter a number to check even or odd 3
Number is ODD

we can be place label anywhere. if the label is after goto statement then the control is transferred forward and this is know forward jump and if the label is before goto statement then control is transfer to the backwards this is known as backward jumping.

note: The control can be transfer with in the function using goto statement not outside of function

When should we use goto?

when the condition in which using goto is preferable is when we need to break or jumps from the multiple loops using a single statement at the same time.

/* goto statement Example*/
#include<stdio.h>
int main()
{
int a, b, c;
for(a=0;a<10;a++)
{
for(b=0;b<5;b++)
{
for(c=0;c<3;c++)
{
printf("%d %d %d\n",a,b,c);
if(b == 3)
{
goto out;
}
}
}
}
out:
printf("out of the loops");
}

0 2 1
0 2 2
0 3 0
out of the loops