Although, for many situations, a series of nested IF statements can perform multiway tests, a built-in multiple-branch decision statement, like SWITCH, is a more efficient approach. When a match is
found, then the statement sequence associated with that match is executed:
switch (expression)
{
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
.
.
.
default
statement sequence
}
where,
default statement -- Is performed if no matches are found. This default is
optional.
In this program, the SWITCH expression must evaluate to either a character or an integer value. The expression, which
controls the switch, is simply a variable.
When a match
is found, then the statements associated with that case are executed until its break is
encountered.
Note that the SWITCH statement in C++ follows:
i) Comparison between SWITCH and IF: SWITCH can only test for equality, while the IF
conditional expression can be of any type.
ii) A SWITCH statement is normally more efficient than nested IFs.
iii) The
entire SWITCH statement does define a block, even though the statement sequences associated with each case are not blocks.
Note that, in DM, there is no switch statement. For instance, Table 1133 shows that a working DM script here is a replacement of switch statement in C++. This script creates a simple "help" system
that describes the meaning of the for, if, and switch statements. It first displays the help topics and then waits for the user to enter a choice.
Table 1133. Comparison between DM and C++ codes with SWITCH statement.
Working DM scripts |
Direct "translation" from C++ |
TagGroup GlobalSino, EMItems
GlobalSino = DLGCreateDialog( "Ask for a help?", EMItems )
TagGroup EMVote1 = DLGCreateCheckBox( "First help ", 0)
TagGroup EMVote2 = DLGCreateCheckBox( "Second help", 0)
TagGroup EMVote3 = DLGCreateCheckBox( "Third help ", 0)
EMItems.DLGAddElement( EMVote1 )
EMItems.DLGAddElement( EMVote2 )
EMItems.DLGAddElement( EMVote3 )
if ( !Alloc( UIframe ).Init( GlobalSino ).Pose() ) exit (0)
if ( 1 == EMVote1.DLGGetValue())
{
Result("Help on FOR in DM\n")
}
if ( 1 == EMVote2.DLGGetValue() )
{
Result("Help on IF in DM\n")
}
if ( 1 == EMVote3.DLGGetValue() )
{
Result("Help on SWITCH in DM\n")
}
Result( "\n\n" )
Script code |
Number a;
Result ("Ask for a help?\n";
Result("10. Help on FOR in DM\n")
Result("20. Help on IF in DM\n")
Result("30. Help on SWITCH in DM\n")
... "Enter choice (10, 20, or 30): ";
switch (a)
{
case 1:
Result ("for is versatile");
break;
case 2:
Result ("IF is conditional");
break;
case 3:
Result ("switch is multiway");
break;
default:
result ("You must enter a number from 10, 20, and 30.\n");
} |
number EMi
for(EMi=0; EMi<4; EMi++)
{
if ( 1 == EMi)
{
Result("Help on FOR in DM\n")
}
if ( 2 == EMi)
{
Result("Help on IF in DM\n")
}
if ( 3 == EMi)
{
Result("Help on SWITCH in DM\n")
}
Result( "\n\n" )
}
Script code |
|
|