Conditional structures: Difference between revisions
Content added Content deleted
m (→case without a default: the error discussed isn’t syntactic) |
Langurmonkey (talk | contribs) |
||
Line 3,895:
=={{header|langur}}==
If and switch expressions always produce a value, even if it's nothing (null). In the shortened forms, you dispense with the keywords (except the first one).
===if expressions===
If expressions are scoped per section.
<syntaxhighlight lang="langur">if
...
} else if
val
...
} else {
val
...
}</syntaxhighlight>
Line 3,916 ⟶ 3,914:
This is more flexible than a ternary operator, as it allows more than one test. An else section is optional (null by default).
<syntaxhighlight lang="langur">if(
===simple if===
Simple if expressions use a colon after the test condition. This is convenient for simple branching or assignments, without having to use curly braces, but does not allow for else if or else sections.
<syntaxhighlight lang="langur">if
===switch expressions===
Line 3,928 ⟶ 3,926:
Switch defaults to testing that any condition is true (as familiar to many programmers), but this can be changed by specifying an infix operator within square brackets, such as switch[and].
<syntaxhighlight lang="langur">switch
case true: ...
# any are true
case false, _: ...
#
case _, null, true: ...
#
case xor _, true, true: ...
#
}
switch 0 {
case
#
...
}
switch[and]
case true: ...
# all are true
case false, _: ...
#
case _, null, true: ...
#
}</syntaxhighlight>
Line 3,958 ⟶ 3,956:
===implicit fallthrough===
If a block of a switch has any statements, there is no implicit fallthrough. A case with an empty block after it creates an implicit fallthrough.
<syntaxhighlight lang="langur">switch
case true:
# implicit fallthrough
Line 3,969 ⟶ 3,967:
A fallthrough statement is allowed anywhere within a switch block, not just at the end. (It's typical in programming languages to only allow fallthrough at the end of the block.)
<syntaxhighlight lang="langur">switch
case true:
if
fallthrough
} else {
Line 3,981 ⟶ 3,979:
===shortened form switch===
A shortened form expects a single action expression per test and is more limited in other ways, as well (no explicit fallthrough, no alternate test expressions, no alternate logical operators). A default section is optional (null by default).
<syntaxhighlight lang="langur">switch(
true: ... ; # any are equal to true
_, >=
... ) # default</syntaxhighlight>
|