Pages

Friday, April 11, 2014

Switch statement in C programming

Switch statement
  • Switch is also a control structure and it is used to select one option from a set of options.
  • It compares the value of an expression or a variable against a list of cases.
  • The case labels and the value of expression or variable must be an integer or a character.
  • It must not be a float or double value. If the value of expression in switch is float or double type then the compiler will generate error message. 
Syntax:

  • The value of expression or variable is compared to each case label.
  • The case whose case value matches the returned value by expression or the value of variable is executed.
  • Multiple cases can also be written in ahead of a case.
For example:
Break Keyword using in Switch statement Cases:
  • Break keyword must be included at the end of each case statement and is used to exit from the body of switch.
What problem occurs when Break keyword is not used with cases?
  • When the value of expression or variable match with a case then body of this case will executed and there is not a break statement due to this all the bodies of below cases will be executed.
The use of Default Keyword in Switch statement:
  • Its use is optional and if none of the case label is matched with the returned value of expression or variable then the statements under default are executed.
  • The of default keyword in sot fixed. It may be placed before the first case or after the last case.

Example: A program to find whether character is vowel or not using Switch statement


Note: If you have any query regarding switch statement comment below.

Related Posts by Categories

0 comments:

Post a Comment