Goto Statement in C

C goto statement

C goto statement:

The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment 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 complecated.

Syntax:

  1. label:
  2. //some part of the code; 
  3. goto label;
goto example

Let’s see a simple example to use goto statement in C language.

#include <stdio.h>

int main()

{

int num,i=1;

printf(“Enter the number whose table you want to print?”);

scanf(“%d”,&num);

table:

printf(“%d x %d = %d\n”,num,i,num*i);

i++;

if(i<=10)

goto table;

}

Output:

Enter the number whose table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

When should we use goto?

The only condition in which using goto is preferable is when we need to break the multiple loops using a single statement at the same time. Consider the following example.

#include <stdio.h>

int main()

{

int i, j, k;

for(i=0;i<10;i++)

{

for(j=0;j<5;j++)

{

for(k=0;k<3;k++)

{

printf(“%d %d %d\n”,i,j,k);

if(j == 3)

{

goto out;

}

}

}

}

out:

printf(“came out of the loop”);

}

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop

Related Post:

Features of C Programming Language

Variables in C

Data Types in C

Keywords in C

C Operators

Comments in C

Escape Sequence in C

C Functions

Storage Classes in C

Dynamic memory allocation in C

Factorial Program in C

Leap year program in C

Fibonacci Series in C

Prime Number program in C

Palindrome program in C

Sum of digits program in C

Escape Sequence in C

ASCII value in C

Difference Between Type Casting and Type Conversion in C

Difference Between Variables and Constants

Matrix multiplication in C

C Program to generate Fibonacci Triangle

C Program to print “hello” without semicolon

C Program to swap two numbers without third variable

C Program to reverse number

Count the number of digits in C

Tokens in C

C Identifiers

C Strings

Compile time vs Runtime in C

C break statement

Type Casting in C

C String Functions

C Pointers

Dangling Pointers in C

void pointer in C

Pointer to Pointer in C

Recursion in C

Call by value and Call by reference in C

File Handling in C

C fprintf() and fscanf()

C fputc() and fgetc()

C fputs() and fgets()

C fseek() function

Constant Pointers in C

4 thoughts on “C goto statement

  1. Pingback: Variables in C - CloudNClear

  2. Pingback: Storage Classes in C - CloudNClear

  3. Pingback: C Functions - CloudNClear

  4. Pingback: Compile time vs Runtime in C - CloudNClear

Comments are closed.