Conditionals
Conditionals
An if
expression specifies that some code should only be evaluated if a certain condition is true. For example:
The condition must be an expression of type bool
.
An if
expression can optionally include an else
clause to specify another expression to evaluate when the condition is false.
Either the "true" branch or the "false" branch will be evaluated, but not both. Either branch can be a single expression or an expression block.
The conditional expressions may produce values so that the if
expression has a result.
The expressions in the true and false branches must have compatible types. For example:
If the else
clause is not specified, the false branch defaults to the unit value. The following are equivalent:
Commonly, if
expressions are used in conjunction with expression blocks.
Grammar for Conditionals
if-expression → if ( expression ) expression else-clauseopt
else-clause → else expression
Last updated