C Language | Switch Statement

Switch statement

• switch statement helps us to apply multiple conditions related to value of a variable.
• The variable used within switch statement can be either an “int” or a “single character” (or an expression can also be given).
• Based on the value of the variable specific set of statements are executed
• Different conditions in switch statement are specified using the keyword “case”.

Syntax:

switch(value/variable/exp)
{
case value1:
      Statements;
      break;
case value2:
     Statements;
     break;
case value3:
    Statements;
    break;

Any number of cases

default:
    Statements;
    break;
}

• On execution of break statement the control jumps out of the switch block.
• If value of the variable does not match with any of the values specified with different cases then set of statements written in default clause get executed.

switch(a) //a is int
{
case 6:
     statements;
     break;
case 10:
    statements;
    break;
case 7:
    statements;
    break;
default:
    statements;
    break;
}

• Default clause is optional.
• Default clause can be given any where in switch block

switch(a) //a is int
{
case 6:
    statements;
case 10:
    statements;
case 7:
    statements;
    break;
default:
    statements;
break;
}

• If required number of cases can be given together

switch(a)
{
case 12:
case 2:
case 10:
    statements;
    break;
case 7:
case 19:
    statements;
    break;
default:
    statements;
    break;
}

For characters

switch(a)// a is single char
{
case ‘A’:
case ‘a’:
    statements;
    break;
case ‘D’:
case ‘d’:
    statements;
    break;
case ‘e’:
case ‘E’:
    statements;
    break;
default:
    statements;
    break;
}

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects

Number Of Visitors

0125451