Saturday, July 13, 2013

The break Statement in C

Break statement in C plays an important role in terminating the control statements. In C, we have many control statements. To get out of the statements in the middle, break is used. Break is generally used in looping statements and in the switch...case statements.

Syntax:
break;

The following example gives you a clear usage of the break statement.

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=5,i;
  5. for( i=0;i<a;i++)
  6. {
  7. if(i==3)
  8. break;
  9. printf("%d\n",i);
  10. }
  11. return 0;
  12. }
The output of the above program is 
0
1
2

If you observe the output carefully, the print has ended up with 2. This is because when i is 3, we have used break to get out of the loop. So the printing has stopped and the control has come out of the loop. 

Note:break gets out of the loops but not for the if condition.

There is another statement in C which just acts like break, which is continue. The difference between these two statements is that, break breaks entire loop, while continue breaks only the current iteration. You can know about continue by clicking here.