Understanding the Goto Statement in C Programming


The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Goto statement in C is a jump statement that is used to jump from one part of the code to any other part of the code in C.


Syntax 1 :
       goto label ;
       . .
       .
       label : statement ;


Syntax 2 :
       label : statement ;
       . .
       .
       goto label ;



The program is written in C and it demonstrates the use of the goto statement.

  • The program starts with the inclusion of the header file "stdio.h" which contains the function printf() used in the program.
  • The program declares an integer variable "i" and initializes it with 0. It then uses the goto statement to jump to a labeled location in the program, which is "joes" in this case. The program then uses the printf() function to print the value of the variable "i" which is initially 0.
  • The program then increments the value of "i" by 1 using the increment operator (++) and checks if the new value of "i" is not equal to 5 using the if statement. If the condition is true, the program jumps back to the labeled location "joes" using the goto statement. This process continues until the value of "i" becomes 5, at which point the if statement condition becomes false, and the program does not jump back to the labeled location.
  • The program then prints "End" and returns 0 to indicate successful execution.
  • It's worth noting that the Goto statement is considered as a bad practice in programming and it makes the program harder to read and understand, and can lead to hard to debug spaghetti code. Instead of using goto statement, programmers should use structured control flow statements like if-else, for, while, do-while, etc.

Source Code

//goto label
#include<stdio.h>
 
int main()
{
    int i=0;
    joes:
    printf("\n%d",i);//0 1 2 3 4
    i++;//1 2 3 4 5
    if(i!=5)
    {
        goto joes;
    }
    printf("\nEnd");
    return 0;
}
 
To download raw file Click Here

Output

0
1
2
3
4
End

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C