goto statement in C

goto statement in C




goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.

Syntax

The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to gotostatement.

Flow Diagram

C goto statement

Example

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

   /* local variable definition */
   int a = 10;

   /* do loop execution */
   LOOP:do {
   
      if( a == 15) {
         /* skip the iteration */
         a = a + 1;
         goto LOOP;
      }
  
      printf("value of a: %d\n", a);
      a++;

   }while( a < 20 );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

            

The exit() function:

  • In C exit() is a predefined/ library function used to terminate the currently running program(process) immediately.
Syntax:  void exit(int status);
  • status -> The status in an integer value returned to the parent process.
  • Here 0 usually means program completed successfully, and nonzero values are used as error codes. e.g exit(0);
  • There are also predefined macros EXIT_SUCCESS and EXIT_FAILURE,  e.g. exit(EXIT_SUCCESS);
  • In the C Language, the required header for the exit( ) function is stdlib.h.
Example:
Sample Output Start of the main()… Exiting the main()…

Comments