Tuesday, February 16, 2016

'switch' Statements



The alternative of nested 'if' statement is called 'switch' statement, which has different statement blocks for different cases. Basically 'switch' statement tries to match evaluated value of an expression against different cases. Syntax of 'switch' statement is as follows.
  1. switch(expression)
  2. {
  3. case value 1:
  4. statement block 1;
  5. break;
  6.  
  7. case value 2:
  8. statement block 2;
  9. break;
  10.  
  11. ...
  12. ...
  13.  
  14. case value n:
  15. statement block n;
  16. break;
  17.  
  18. default:
  19. default statement block;
  20. break;
  21. }
The expression 'expression' is evaluated first and the value is checked with different case values (value 1, value 2, ... etc. If one of the case values matches the result of expression, then respective statement block is executed. If none is matched, then the statement block of 'default' case is executed. You may notice another keyword in the switch statement which is break. If break keyword is omitted, all the the statements after that will be executed even if the corresponding case values do not match the value of expression. This is called a 'fall through' statement. For example, if 'break' is omitted and say, case 'value 1' is matched, then after execution of 'statement block 1' the code will execute statement block 2, 3 and so on until a 'break' statement is reached.

Rules for Writing 'switch' Statements in C Language

  • The values of case label must be unique, else complier will throw error
  • The values of case should be an integral constant (integer or character). If any variable is specified as part of a case, compiler will throw error, but a 'const' variable is allowed.
  • The 'default' case is optional and it can be placed anywhere in the switch block.
  • 'switch' statements can be nested; that means you can have another 'switch' statement as part of a statement block associated with a case.
  • The statement block of a case is optional and it can be shared by more than one cases.

Example of 'switch' Statement

We can rewrite the program to check if a number is even or odd using switch statement as given below.
  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4.  
  5. int i = 5;
  6. switch(i % 2)
  7. {
  8. case 0:
  9. printf("%d is even number", i);
  10. break;
  11.  
  12. case 1:
  13. printf("%d is odd number", i);
  14. break;
  15. // We do not need default case here as there can only be two cases 0 or 1.
  16. }
  17. return 0;
  18. }
  19.  
  20. Output:
  21. 5 is odd number

No comments: