switch statement

< c‎ | language
Revision as of 14:17, 17 April 2013 by Dieram3 (Talk | contribs)

Executes code according to value of an integral argument

Used where one or several out of many branches of code need to be executed according to an integral value.



switch ( Template:sparam ) {
case Template:sparam :
Template:sparam (optional)
case Template:sparam :
Template:sparam (optional)
... ... ...
case Template:sparam :
Template:sparam (optional)
default: Template:sparam (optional)



Template:sparam shall be an expression, convertible to an integer value.

All Template:sparams shall be constant expressions, convertible to an integer value, which is unique within this switch statement

If the Template:sparam evaluates to a value, equal to the value of one of the defined Template:sparam, the Template:sparam (if present) and all subsequent statements (including Template:sparam, if present) are executed. If the value of the Template:sparam does not match any of the Template:sparams, the Template:sparam is executed if present.

It is useful to note, that if the execution of subsequent statements is undesirable, the break statement can be used. In that case the execution of the switch statement terminates.


switch, case, default


#include <stdio.h>
void func(int x)
   printf("func(%d): ", x);
      case 1: printf("case 1, ");
      case 2: printf("case 2, ");
      case 3: printf("case 3.\n"); break;
      case 4: printf("case 4, ");
      case 5: printf("case 5, ");
      default: printf("default.\n");
int main()
   for(int i = 1; i < 10; ++i)  func(i);


func(1): case 1, case 2, case 3.
func(2): case 2, case 3.
func(3): case 3.
func(4): case 4, case 5, default.
func(5): case 5, default.
func(6): default.
func(7): default.
func(8): default.
func(9): default.