goto in C

Previous
Next

goto:

  • It is a keyword.
  • It is a branching statement
  • It is used to send the cursor from one location to another location in C program.
  • Goto statements transfer the control using labels.
  • Label is an identity followed by colon(:)
  • Label should follow the rules of identities.
#include<stdio.h>
int main()
{
	int a=1;
	
	top:
	printf("a value : %d \n", a);
	++a;
	return 0;	
}

We must use goto statement to transfer the control using labels:

#include<stdio.h>
int main()
{
	int a=1;
	
	top:
		printf("a value : %d \n", a);
		++a;
	
		if(a<=10)
			goto top;
	return 0;	
}

We can create multiple labels in a single program.

#include<stdio.h>
int main()
{

	top:
		printf("Top \t");
		
	center:
		printf("Center \t");
	
	bottom:
		printf("Bottom \n");
		goto top;
		
	return 0;	
}

Check this code:

#include<stdio.h>
int main()
{

	top:
		printf("Top \t");
		goto bottom;
		
	center:
		printf("Center \t");
	
	bottom:
		printf("Bottom \n");
		goto top;
		
	return 0;	
}

We use goto statement to come out of infinite loop also.

#include<stdio.h>
int main()
{

	while(1)
	{
		printf("Infinite loop \n");
		goto end;
	}
	
	end:
		printf("Can break with goto\n");
		
	return 0;	
}

Check the code:

#include<stdio.h>
int main()
{
	int x=3;
	switch(x)
	{
		case 0 : printf("C is damn easy \n");
		case 1 : printf("C is easy \n");
		case 2 : printf("C is bit complex \n");
		defalt : printf("C is difficult \n");
	}		
	return 0;	
}
  • In the above code “default” spelled incorrectly.
  • Compile will not generate any error.
  • Program output is blank.
  • In the above program ‘defalt’ is consider as goto label.
  • As we are not writing goto statement the corresponding statement is not executing
Previous
Next

Add Comment

Courses Enquiry Form