What is Switch Case in C ?

What is Switch case in C ?

In this article we will discuss about Switch Statement topic of C in detail in which following topics are included:

  • What is Switch case in C ?
  • Syntax of Switch case in C ?
  • Example of Switch case in C ?

What is Switch Case in C ?

C has built-in multi way decision statement know as a switch. The switch statement tests the value of given variable(or expression) against the list of case value and when a match is found, a block of statement associated with the case is executed.

Syntax of Switch case in C

switch(expression)

{
   case value-1:
                block-1
                break;
   case value-2:
                block-2
                break;
   case value-3:
                block-3
                break;
   .
   .
   .
   case value-n
               block-n
               break;
   default
               default-block
               break;
}
statement-x;


Important Point:

  • The break statement at the end of each block signals the end of particular case and causes an exit from the switch statement transferring the control of statement-x following the switch.
  • The default is an elective case.When gift,it will be executed if the fee of the expression does now not suit with any of the case values.If not present,no action takes vicinity if all matches fail and the manipulate goes to the statement-x.

Rules for Switch Statement:

  • The switch expression must be an expression type.
  • Case labels must be constant or constant expression.
  • Each case label must be unique.No two labels can have the same value.
  • Case label must be end with colon(:).
  • The break statement is optional. i.e, two or more case labels may belong to same statements.
  • The default label is optional. if present, it will executed when the expression does not find a matching case label.
  • There can be at most one default label.
  • The default place anywhere but usually placed at the end.
  • It is permitted to nest switch statement.

Example of Switch Case in C

example of switch case

Conclusion:

In this article we have learnt about  Switch case  of C in detail with example and its syntax.
I hope after reading this article you have no any doubt remaining  in this topic but if you any doubt left then feel free comment below.

___________________________________________

Post a Comment (0)
Previous Post Next Post