Learn C Language : Switch Case Statement (Case Control Structure)

Switch Case Statement

The control statement which allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement.

Syntax of switch statement:

switch(expression)
{
case constant 1:
do this;
case constant 2:
do this;
case constant 3:
do this;
default:
do this;
}

 

The integer expression following the keyword switch is any C expression that will yield an integer value.It could be an integer constant like 1, 2 or 3, or an expression that evaluates to an integer.The keyword case is followed by an integer or a character constant.Each constant in each case must be different from all the others.The ‘do this’ lines in the above form of switch represent any valid C statement.

A simple program which demonstrates the use of continue statement:

main()
{
int i = 2;
switch(i)
{
case 1:
. printf(“I am in case 1”);
case 2:
printf(“I am in case 2”);
case 3:
printf(“I am in case 3”);
default:
printf(“I am in default”);
}
}

Output :
I am in case 2
I am in case 3
I am in default

Switch statement using break:

main()
{
int i = 2;
switch(i)
{
case 1:
printf(“I am in case 1”);
break;
case 2:
printf(“I am in case 2”);
break;
case 3:
printf(“I am in case 3”);
break;
default:
printf(“I am in default”);
}
}

Output :
I am in case 2

 

Leave a Comment