Conditional structures: Difference between revisions

Content added Content deleted
m (→‎case without a default: the error discussed isn’t syntactic)
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).
 
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 .x == 0 {
...
} else if .x > 0 {
val .y = 100
...
} else {
val .y = 70
...
}</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(.x > .y: ...; .x < .y: ...; /* else */ ...)</syntaxhighlight>
 
===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 .x > .y: break</syntaxhighlight>
 
===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 .x, .y, .z {
case true: ...
# any are true
case false, _: ...
# .x == false
case _, null, true: ...
# .y == null or .z == true
case xor _, true, true: ...
# .y == true xor .z == true
}
 
switch 0 {
case .x, .y: ...
# .x or .y equals 0
...
}
 
switch[and] .x, .y, .z {
case true: ...
# all are true
case false, _: ...
# .x == false
case _, null, true: ...
# .y == null and .z == 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 .x {
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 .x {
case true:
if .y > 100 {
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(.x, .y, .z;
true: ... ; # any are equal to true
_, >= .z: ...; # .y >= .z
... ) # default</syntaxhighlight>