Next page | Contents page |

Conditional statements (2) - switch

Syntax:

	switch (expression)
	{
	 case value1:
			statements
	 case value2:
			statements
	   ...
	 default: statements  
	}

If the expression evaluates to value1, execution inside the braces starts after the label value1:. Similarly for any other values that are given as cases. If none of the case values matches, the default section is executed.

The default section is optional. If it is not there, execution just continues after the ending brace of the switch.

Example:

	switch (keyCode)
	{
	case insKey: insert ();
			break;
	case backKey:
	case delKey: delete ();
			break;
	default: append (keyCode);
	}

It is usual to put break; at the end of each section to make execution jump out there and continue after the ending brace of the switch. If the break; is not there, execution continues into the next case section; sometimes that is desired, as in the backKey case in the example above.

Constraints on the switch statement

Next page | Contents page |