.DT switch $MUDNAME$ driver help switch .SH Name .SI 5 switch() - an alternative to lots of if statements .EI .SH Synopsis .SI 5 switch( value ) { case(s): default: } .EI .SH Description .SP 5 5 Switch is an easier way of comparing values to a number of criteria than using long chains of if statements. The 'value' is held in memory and is checked against each case. The 'break' reserved word breaks out of the switch, and the 'default' reserved word is executed if none of the other cases match. It's less CPU-demanding than if statements. .EP .SH Example 1 .SI 5 First, let's try a series of if statements, then rewrite it using a switch. int x = 4; if( x > 10 ) write("X is greater than 10.\n"); else if( x < 0 ) write("X is less than 0.\n"); else if( x > 5 ) write("X is between 5 and 10.\n"); else write("X is between 0 and 4.\n"); Now, we rewrite it with a switch(). int x = 4; // We'll assume that x won't be too big or too small. switch( x ) { case 10..100: write("X is greater than 10.\n"); break; case -100..0: write("X is less than 0.\n"); break; case 5..9: write("X is between 5 and 10.\n"); break; default: write("X is between 0 and 4.\n"); } In both cases, the result was "X is between 0 and 4.", but see how much easier the switch() was to write and understand? .EI .SH Example 2 .SI 5 string str = "zot"; switch( str ) { case "zip": write("Zip zip zip!\n"); break; case "zap": write("Zap!\n"); break; case "zot": write("Zzzzzzot!\n"); break; default: write("Zipper!\n"); } The result: "Zzzzzzot!" was printed. .EI .SH See also .SI 5 if, else .EI