break, continue, exit() and goto

The break statement:

It is a keyword used with loop and switch case to transfer the control to outside the block.  Syntax: break;

  • When the break statement is encountered inside a loop, the loop is immediately terminated and program control jump to the next statement following the loop.
  • When it is used with Switch statement it terminate a case and the control jumps to the next statement following the switch case
  • It is normally used with conditional if statements

Example:

 

 The continue statement:

  • It is a keyword used to transfer the control to the beginning of the loop skipping the remaining statements inside the loop.

Syntax: continue;

  • Like break it is used with conditional if statements

Example:

Output:Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello

Output:
1       1
2       2
3       3

 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()…

 The goto statement:

  • The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally.

Syntax:

  • label is an identifier, so it follows the identifier rules for naming convention
  • When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code below it.
  • Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.
  • It rarely used in the program, it makes program confusing, less readable and complex. Also, when this is used, the control of the program won’t be easy to trace, hence it makes testing and debugging difficult.
  • It is advisable to not to use goto statement in program

Demo program of goto:

Sample Input/Output:
How many numbers You want to consider? 5
Enter only +ve numbers. -ve number will make use of goto.
Enter n1: 5
Enter n2: 4
Enter n3: 8
Enter n4: -7
Average: 5.6667