Branching

From Apache OpenOffice Wiki
Jump to: navigation, search


Use branching statements to restrict the execution of a code block until a particular condition is satisfied.

If...Then...Else

The most common branching statement is the If statement as shown in the following example:

IfA>3Then
B=2
EndIf

The B = 2 assignment only occurs when value of variable A is greater than three. A variation of the If statement is the If/Else clause:

IfA>3Then
B=2
Else
B=0
EndIf

In this example, the variable B is assigned the value of 2 when A is greater than 3, otherwise B is assigned the value of 0.

For more complex statements, you can cascade the If statement, for example:

IfA=0Then
B=0
ElseIfA<3Then
B=1
Else
B=2
EndIf

If the value of variable A equals zero, B is assigned the value 0. If A is less than 3 (but not equal to zero), then B is assigned the value 1. In all other instances (that is, if A is greater than or equal to 3), B is assigned the value 2.


A complete If statement may be written on a single line, with a simpler syntax. The first example of this page may be written as:

IfA>3ThenB=2

The second example of this page may be written as:

IfA>3ThenB=2ElseB=0

Select...Case

The Select...Case instruction is an alternative to the cascaded If statement and is used when you need to check a value against various conditions:

SelectCaseDayOfWeek
Case1:
NameOfWeekday="Sunday"
Case2:
NameOfWeekday="Monday"
Case3:
NameOfWeekday="Tuesday"
Case4:
NameOfWeekday="Wednesday"
Case5:
NameOfWeekday="Thursday"
Case6:
NameOfWeekday="Friday"
Case7:
NameOfWeekday="Saturday"
EndSelect

In this example, the name of a weekday corresponds to a number, so that the DayOfWeek variable is assigned the value of 1 for Sunday, 2 for Monday value, and so on.

The Select command is not restricted to simple 1:1 assignments — you can also specify comparison operators or lists of expressions in a Case branch. The following example lists the most important syntax variants:

SelectCaseVar
Case1To5
' ... Var is between the numbers 1 and 5 (including the values 1 and 5).
Case>100
' ... Var is greater than 100
Case6,7,8
' ... Var is 6, 7 or 8
Case6,7,8,>15,<0
' ... Var is 6, 7, 8, greater than 15, or less than 0
CaseElse
' ... all other instances
EndSelect

Now consider a misleading (advanced) example, and a common error:

SelectCaseVar
CaseVar=8
' ... Var is 0
CaseElse
' ... all other instances
EndSelect

The statement (Var = 8) evaluates to TRUE if Var is 8, and FALSE otherwise. TRUE is -1 and FALSE is 0. The Select Case statement evaluates the expression, which is TRUE or FALSE, and then compares that value to Var. When Var is 0, there is a match. If you understand the last example, then you also know why this example does not do what it appears

SelectCaseVar
CaseVar>8AndVar<11
' ... Var is 0
CaseElse
' ... all other instances
EndSelect


Content on this page is licensed under the Public Documentation License (PDL).



AltStyle によって変換されたページ (->オリジナル) /