The if-else set of keywords allow you to specify that different sequences of instructions should be performed depending on some condition. The syntax is:
•The keyword if is followed, on the same line, by a branching condition (a Boolean expression).
•A block of instructions then follows, which are performed if the condition above is true. That block finishes when it reaches either else or endif.
•If an else keyword is present, then the block of instructions between else and endif will be performed if the branching condition is false. Note that having an else block is optional.
Below is an example of the syntax:
bIsLeapYear = IsLeapYear()
if bIsLeapYear
nDayInFeb = 29
bRESULT = true
sResult = 'Feb has 29 days'
else
sResult = 'Feb has only 28 days'
nDayInFeb = 28
bRESULT = false
endif
The blocks performed depending on the branching condition are normal code blocks, which can contain other nested blocks. For example, we could modify the above:
bIsLeapYear = IsLeapYear()
if bIsLeapYear
nDayInFeb = 29
bRESULT = true
if YearOf(Today()) == 2000
sResult = 'Yes, Feb has 29 days in 2000 !!!'
else
sResult = 'Feb has 29 days'
endif
else
sResult = 'Feb has only 28 days'
nDayInFeb = 28
bRESULT = false
endif
In the above, if we are in a leap year, then we have added an extra branching condition that checks to see if we are in the year 2000. If that is the case we make the message more emphatic, since many people mistakenly think that the year 2000 is not a leap year
If you only need to perform some instructions if a condition is not true you should use the following:
if not IsLeapYear()
// do something
endif
This solution is compact and legible.
See also: branching with the switch keyword.
Topic 105131, last updated on 18-Apr-2020