Switch Statement in C

switch statement in c.jpg

Switch Case in C

A switch statement allows equality checking of an attribute against a set of values. Each attribute is called a case, and for each switch case in C, the variable to be turned on is checked. With Switch statements, users can describe different statements for the differing values of a single variable in numerous cases.

Syntax

Here is the syntax of the switch statements in the C language:


switch(expression)
{    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
......     
default:     
 code that is be executed if all the cases are not matched;    
}    


For a switch statement − the following rules apply

  • The term used in a switch statement in C must be of an integral or enumerated type, or of a class type where the class has an integral or specified type with a different conversion function.
  • Inside a switch, you can get any number of case statements. Each case is accompanied by the meaning and a colon to be matched with.
  • In an event, the static-expression must be the same data form as the switch variable, so it must be a constant or a literal one.
  • If the variable to be turned on is identical to a case, the statements after that case will be executed before a breakpoint has been reached.
  • Once a break statement is reached, the switch will stop, and the control flow will transfer to the next line after the switch declaration.
  • Not every event has a break in it. If no break occurs, the control flow will fall into subsequent cases before a break is reached.
  • An optional default case can have a switch comment, which must appear at the end of the switch. If none of the cases is valid, the default case may be used to perform a function. In the default case, no break is required.
Flow diagram of Switch Statement

Switch Statement in C,jpg
Read More...
Also, Visit Here  C programming tutorial

Comments

Popular posts from this blog

C Pointers

C Programming Language Tutorial