C Programming

Break and continue

The break statement

The break statement is used when we don't want further iterations of the loop. When break is encountered inside any loop, control automatically passes to the first statement after the loop.

Syntax

break;

Example

We said earlier that testing part of for loop is also optional.Without the break statement, an infinite loop will occur. Now with the help of the break statement, we will get out of the loop.

#include "stdio.h"
int main()
{
  int i = 1, j;
  for ( ; ; )
{ 
    if (i)
        j = --i;
    if (j < 10)
       printf("GeeksQuiz", j++);
    else
       break;
  }
  return 0;
}

Basically, even though the for loop doesn't have any of three expressions in parenthesis, the initialization, control and increment have been done in the body of the loop. So j would be initialized to 0 via first if. This if itself would be executed only once due to i--. Next if and else blocks are being used to check the value of j and existing the loop if j becomes 10. Please note that j is getting incremented in printf even though there's no format specifier in format string. That's why GeeksQuiz would be printed for j=0 to j=9 i.e. a total of 10 times.

The continue statement

The continue statement is similar to break statement instead of terminating the loop, it forces to execute the next iteration of the loop.

Syntax

continue;

Example

// How many times GeeksQuiz is printed
#include<stdio.h>
int main()
{
    int i = -5;
    while (i <= 5)
    {
        if (i >= 0)
            break;
        else
        {
            i++;
            continue;
        }
        printf("GeeksQuiz");
    }
    return 0;
}

The loop keeps incrementing i while it is smaller than 0. When i becomes 0, the loop breaks. So GeeksQuiz is not printed at all.

The goto statement

The goto statement is used to perform an unconditional jump from goto to label.

Syntax

goto label;

label: //code

Example

#include "stdio.h"
int main()
{
  int i; 
  goto LOOP;
  for (i = 0 ; i < 10 ; i++)
  {
     printf("GeeksQuiz\n");
     LOOP:
      break;
  }
  return 0;
}

goto statement can be used inside a function and its label can point to anywhere in the same function. Here, for loop expressions i.e. i = 0 and i < 10 and i++ wouldn’t be executed at all. Because goto would make the program jump directly inside the for loop. And from there, it’ll execute break statement which would exit the loop. So effectively nothing would be printed.


Recent Comments

Feedback

For any feedback,email us at feedback@geeksforgeeks.org

Report a Bug

For any report or bug,email us at support@geeksforgeeks.org