Introduction
C Programming
C Advanced
Important C Programs
Switch - Break
Switch In Programming :
If we have the scenario of nested if, then switch statement is faster than nested if…else (not always). Also, the syntax of switch statement is cleaner and easy to understand.
In switch statement, we provide a value that is to be compared with a value associated with each option. Whenever the given value matches with the value associated with an option, the execution starts from that option. In switch statement every option is defined as a case.
Break Statement :
The break statement in programming is used for two following purposes :
- break can be used to terminate a case in the switch statement as in above given example.
- break statement inside a loop, is used to terminate the program control and resumes at the next statement following the loop.
Break statement breaks the loop even if the condition is true ( explained in next section with loop examples).
General example based on switch - break
switch (a)
{
case 1:
// this part executes if a is 1
break;
case 2:
// this part executes if a is 2
break;
// and so on, multiple cases may be placed here.
default:
// if a is not matched with any case, then this part executes.
}
Video/ C Introduction
Watch video in full size