How to use Switch Statement in C - Programmer's Mind


Switch Statement in Programming

Switch is a multi way selection Statement in C Programming.
Switch is a sequential control statement

Syntax for Switch Statement is as Follows 

switch(choice)
{
  case label1: statements;
                     break;

  case label2: statements;
                     break;
  case label3: statements;
                     break;
  case label4: statements;
                     break;
.
.
.
.
.
 default:statements;
            break;

}

Explanation for Switch case execution:

     Whenever program control enters into the switch statement it will searches for the matching case label for choice.If a label of  switch case matches with the choice, then the block of statements in that switch case will be executed.If there is no matching label then control switches to the default block.

Example Program using switch-case:


#include<stdio.h>
void main()
 {
  int choice=2;
  switch(choice)
  {
   case 1:printf("Sunday");
 break;
   case 2:printf("Monday");
 break;
   case 3:printf("Tuesday");
 break;
   case 4:printf("Wednesday");
 break;
   case 5:printf("Thursday");
 break;
   case 6:printf("Friday");
 break;
   case 7:printf("Saturday");
 break;
   default:printf("Invalid choice");
           break;
  }
 }

Facts about switch statement in C


1. switch case labels must be unique.Otherwise compiler generates an error Duplicate case

switch case

2. Default case is optional in Switch statement.Switch statement will compile and run successfully without default case.But there should not be more than on default case in Switch otherwise compiler generates an error Too many default cases.We can place default statement at anywhere in the
switch case.There is no rule that default should placed at last or first.


switch case

3. Switch Case labels must be constants.They should not be floating point numbers or conditions(Relational Operators) otherwise compiler generates an error constant expression required    


4. Break is not a mandatory one in switch case.
what happens if we skip break in switch case??
If we skips the break after the block of statements in switch case then program control will transfers to the next cases until it finds either a break or end of switch statement

5. In switch, every case label should ends with a colon ":" otherwise compiler generates an error Case statement missing : 


Next Post:

Loops in C programming
Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment