if and else provide conditional execution of statements. Syntax is:
if (boolean expression) {statements}[
else if (boolean expression) {statements}] ...[
else {statements}]
Only one group of statements will execute:
if's boolean expression evaluates to true, its associated
statements will execute.else if's
boolean expression evaluates to true, its associated statements will
execute.
... else if ... is equivalent to ... else { if ... }, but without
visible nesting of braces.else's associated
statements will execute.When a boolean expression evaluates to true, no later boolean expressions will evaluate.
Note that else if may be repeated.
For example:
if (fruit.IsYellow()) {
Print("Banana!");
} else if (fruit.IsOrange()) {
Print("Orange!");
} else if (fruit.IsGreen()) {
Print("Apple!");
} else {
Print("Vegetable!");
}
fruit.Eat();
This code will:
fruit.IsYellow():
True, print Banana! and resume execution at fruit.Eat().False, evaluate fruit.IsOrange():
True, print Orange! and resume execution at fruit.Eat().False, evaluate fruit.IsGreen():
True, print Apple! and resume execution at
fruit.Eat().False, print Vegetable! and resume execution at
fruit.Eat().if and else