Explain switch statement with Example
The C switch allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements:
switch(expression)
{
case item1:
statement1;
break;
case item2:
statement2;
break;
case itemn:
case itemn:
statementn;
break;
default:
statement;
break;
}
In each case the value of itemi must be a constant, variables are not allowed.
The break is needed if you want to terminate the switch after execution of one choice. Otherwise the next case would get evaluated. Note: This is unlike most other languages.
We can also have null statements by just including a; or let the switch statement fall through by omitting any statements(see e.g. below).
The default case is optional and catches any other cases.
For example:-
switch(letter)
{
case `A':
case `E':
case `I':
case `O':
case `U':
numberofvowels++;
break;
case ‘ ‘:
numberofspaces++;
break;
default:
numberofconsonants++;
break;
}
In the above example if the value of letter is ‘A', ‘E', ‘I', ‘O' or ‘U' then numberofvowels is incremented.
If the value of letter is ‘ ' then numberofspaces is incremented.
If none of these is true then the default condition is executed, that is numberofconsonants is incremented.