The if/else statements are control structures and are used for flow control within the ruleset. They are an elementary part of the ruleset. If a condition is fulfilled, an action is executed, otherwise an alternative action is executed. The action to be executed can always be only one command. If several commands are to be executed as an action, these individual commands can be combined in an instruction block. An instruction block is written within braces.
If defines which prerequisite must be fulfilled for an action to be executed, while else initiates an alternative action if the condition required by if is not fulfilled. An if/else statement does not need be closed with a semicolon. if/else statements can be nested.
A leading exclamation mark "!" for a command within the query inverts the function of the command.
Structure of an if/else statement
if (condition) {
instruction block 1;
}
or
if (!condition) {
instruction block 1;
}
or
if (condition) {
instruction block 1;
} else {
instruction block 2;
}
or
if (condition) {
instruction block 1;
} else if (condition) {
instruction block 2;
} else {
instruction block 3;
}
The if statement determines the further course of the programme on the basis of the return value of the Condition. The condition consists of a single command which has at least one return value.
Instruction block 1 is only executed if the return value is positive. Otherwise, only instruction block 2 is executed.
Example
a)
Line |
Code |
---|---|
01 |
if (authenticated()) { |
02 |
} else { |
03 |
createaccount(); |
04 |
log(1,'user account generated'); |
05 |
} |
b)
Line |
Code |
---|---|
01 |
if (!authenticated()) { |
03 |
createaccount(); |
04 |
log(1,'user account generated'); |
05 |
} |
Explanation
Example a) evaluates the return value of the authenticated() command. If the internal sender of the email could be authenticated successfully, due to the negation, the return value is true. Since no further instruction has been defined for this case, the programme continues without further action. If the authentication has failed, i.e. if the return value is false, the instruction block indicated under else applies. In the example, a user account would be created for the sender, and an OpenPGP key pair would be generated.
In example b) the function of the authenticated() command is inverted by the leading ! in !authenticated(), by means of which the subsequent instruction block corresponds to the else condition in example a).
The programming result of both variants will therefore be the same.