If-else statements and switch statements are two kinds of conditional statements.
if (i == 0) { // an if-else statement ... } else if (i == 1) { ... } else if (i == 2) { ... } else { ... }
switch (i) { // a switch statement case 0: ... break; case 1: ... break; case 2: ... break; default: ... }
Switch statements are actually nested if-else statements. Each case within a switch statement corresponds to a condition in the if-else statement. If-else statements are more powerful than switch statements, since the conditions of if-else statements are C expressions, while the cases in switch statements must be constants.
If-else statements can be easily modeled in DCharts. The guards in the transitions test the different cases, and the outputs perform the actions that correspond to those cases.
Figure 5.4 depicts an example of the transformation from an if-else conditional statement into guards of multiple transitions. Suppose cond_stm is such an if-else statement:
if (x == 0) stm1; else if (x == 1) stm2; else if (y == 0) stm3; else if (y == 1) stm4; else stm5;
In the upper part, the model has a transition from state A to B reacting to event e. The transition is enabled only if the guard i==1 is satisfied. It executes cond_stm as an output. This is not a valid DCharts model, since it violates the restriction of the action code. It is transformed into the valid DCharts model in the lower part. A transition is created for each condition in the if-else statement. The test cases of the conditions are added to the guards. For example, the first test case is x==0. It is added to the guard of the first transition. The second test case is x==1 on the basis that the first test case is not satisfied. As a result (x!=0) && x==1 is added to the guard of the second transition. The third test case is y==0 is on the basis that neither the first test case nor the second test case is satisfied. As a result (x!=0 && x!=1) && y==0 is added to the guard of the third transition. And so on.
If any statement in stm1 to stm5 is not a simple statement or a list of simple statements, further transform the model with the algorithm in section 5.5.2. If the model has other conditional statements, or stm1 to stm5 contain conditional statements, transform those conditional statements with the same method.