Switch Statement In C Language With Examples



The switch Statement:

This is a multi-branch statement similar to the if - else ladder (with limitations) but clearer and easier to code.

Syntax
switch ( expression )
{
case constant1 :   statement1 ;
		break ;

case constant2 :   statement2 ;
		break ;
...
default :   statement ;
}
flow chart of switch statement in c

The value of expression is tested for equality against the values of each of the constants specified in the case statements in the order written until a match is found. The statements associated with that case statement are then executed until a break statement or the end of the switch statement is encountered.

When a break statement is encountered execution jumps to the statement immediately following the switch statement.

The default section is optional -- if it is not included the default is that nothing happens and execution simply falls through the end of the switch statement.

The switch statement however is limited by the following

  • Can only test for equality with integer constants in case statements.
  • No two case statement constants may be the same.
  • Character constants are automatically converted to integer.

For Example :- Program to simulate a basic calculator.

CODE/PROGRAM/EXAMPLE
#include <stdio.h>
void main()
{
  double num1, num2, result ;
  char op ;
 while ( 1 )
  {
	printf ( " Enter number operator number\n" ) ;
	scanf ("%f %c %f", &num1, &op, &num2 ) ;
	_flushall() ;
	switch ( op )
	{
	case ‘+’ :  result = num1 + num2 ;
				   break ;
	case ‘-’ :   result = num1 - num2 ;
				   break ;
	case ‘*’ :  result = num1 * num2 ;
				   break ;
	case ‘/’ :  if ( num2 != 0.0 ) {
result = num1 / num2 ;
break ;
}
	 // else we allow to fall through for error message
	
	default :  printf ("ERROR -- Invalid operation or division by 0.0" ) ;
	}
	printf( "%f %c %f = %f\n", num1, op, num2, result) ;
  }      /* while statement  */
}
Notepad

NOTE : The break statement need not be included at the end of the case statement body if it is logically correct for execution to fall through to the next case statement (as in the case of division by 0.0) or to the end of the switch statement (as in the case of default : ).

#switch_statement_in_c_language #switch_case_in_c #switch_statement_in_c #switch_c #switch_case_program_in_c #switch_case_example_in_c #switch_syntax_in_c #flow_chart_of_switch_in_c

(New page will open, for Comment)

Not yet commented...