Switch Statement

Written By -

switch Statement

 

Switch statement is used to make choices between multiple options. This is similar situation we face in our life, like, Which college to study, Which car to buy, etc.

Switch statements in C language allows to handle these kind of situations more effectively.

Switch statements allows to test for equality against number of choice and each choice is called as case.

The syntax of switch statement is as follows:

switch(expression)
{
Case Constant 1:
Statements;
Case Constant 2:
Statements;
.
.
.
default:
Statements;
}

Example :

#include <stdio.h>

int main()
{
int a = 8;
switch(a)
{
case 1:
printf(“Case1: Value is: %d”, a);
case 2:
printf(“Case2: Value is: %d”, a);
case 3:
printf(“Case3: Value is: %d”, a);
dault:
printf(“Default: Value is: %d”, a);
}
return 0;
}

Output :

Default: Value is: 8

Points To Ponder :

  • The expression in switch case must be a integer or character constant.
  • There is no need to enclose the statements in braces (like in if-else statements).
  • Here, default case is optional. If there is no default case, the next instruction is executed .
  • The expression must be as same data type as the choices/case.
  • The statement inside a choice/case are executed until the break statement is found.
  • Each and every statement must belong to some case or the other.

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019