Tuesday, May 15, 2007

More selection structure

Another selection structure which achieves multiple branching is the switch() structure. This structure is a multiple if() and the broadest use it to create a menu structure for a program.
switch(integer variable)
{
case C1: //Write statements to do if variable == C1
break;

case C2: //Write statements to do if variable == C2
break;

default: //Write statements to do if variable is other values
}
Things to note for a switch() structure:
  • it can only evaluate an integer value (including char)
  • values for the cases are exact values and it does not allow range of values (e.g. C1 > 20)
  • all cases should have a break statement to prevent statements from falling through

No comments: