Conditional structures: Difference between revisions

m
→‎case without a default: the error discussed isn’t syntactic
m (→‎{{header|Forth}}: fix markup)
m (→‎case without a default: the error discussed isn’t syntactic)
 
(33 intermediate revisions by 25 users not shown)
Line 2:
{{Control Structures}}
[[Category:Simple]]
[[Category:Flow control]]
 
;Task:
Line 587 ⟶ 588:
);</syntaxhighlight>
====case expressions====
Using the same example above, we assume that the <syntaxhighlight lang="ada">''Operation</syntaxhighlight>'', <syntaxhighlight lang="ada">''Op</syntaxhighlight>'', and <syntaxhighlight lang="ada">''Result</syntaxhighlight>'' variables are declared. A case expression over the enumeration of operations might look like:
<syntaxhighlight lang="ada">Result := (case Op is
Add => A + B,
Line 596 ⟶ 597:
</syntaxhighlight>
Note: some websites (particularly [https://www.radford.edu/nokie/classes/320/abe/operators.html#:~:text=if%20and%20case-,Examples%3A,1%2C%20others%20%3D%3E%200)%3B this one]) contain a different variant of a case expression (<syntaxhighlight lang="ada">case Op of...</syntaxhighlight>). The Ada Reference Manual indicates this is incorrect, and we use the [http://www.ada-auth.org/standards/12rm/html/RM-4-5-7.html formal version] here.
 
===case with a default alternative===
<syntaxhighlight lang="ada">type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
Line 613 ⟶ 615:
===case without a default===
When there is no '''when others''' clause, the compiler will complain about any uncovered alternative. This defends against a common reason for bugs in other languages.
I.e., the following code is syntactically incorrect:
 
<syntaxhighlight lang="ada">case Today is
Line 625 ⟶ 627:
end case;</syntaxhighlight>
 
The syntactically correct version:
 
<syntaxhighlight lang="ada">case Today is
Line 800 ⟶ 802:
a + b is three
two
</pre>
 
=={{header|Amazing Hopper}}==
Las estructuras condicionales en Hopper son inexistentes. Pero se pueden definir estructuras de alto nivel, todas las que su imaginación le dicte... Bueno, todas las que Hopper le permita hacer con sus instrucciones. Existen instrucciones que permiten evaluar el contenido de la memoria, como "eq?", que evalúa si dos valores son iguales, o "zero?", que evalúa si el valor es cero. También cuenta con saltos condicionales que evalúan el contenido de la memoria, como "jle( etiqueta )", que saltará a etiqueta si el primer valor en memoria es menor o igual al segundo valor en memoria.
Hasta ahora se han definido cuatro "sabores" para Hopper. Aquí repasaremos las estructuras condicionales del sabor "Jambo".
 
OBSERVACION: todas estas estructuras condicionales permiten anidamiento.
 
La más clásica:
 
<pre>
If ( expresion )
...
Else If ( expresion )
...
Else
...
End If
</pre>
 
La definición de las macros para "IF/ELSE" es la siguiente (jambo.h):
 
<pre>
#defn ElseIf(__X__) jmp(%%CODEIF), %ENDIF:, #OPTIMLOG, #ATOM#CMPLX ,#OPTIMLOG, jnt(#ENDIF),
#defn If(__X__) ##CODEIF, #OPTIMLOG, #ATOM#CMPLX ,#OPTIMLOG, jnt(#ENDIF),
#defn Else jmp(%%CODEIF), %ENDIF:, true,jnt(#ENDIF),
#defn EndIf %CODEIF:, %ENDIF:,
</pre>
 
La macro "MOVE IF", mueve un valor desde la memoria hasta una variable, según si se cumple una expresión lógica. El valor es quitado de la memoria. En el ejemplo, moverá "15" a la variable "x":
 
<pre>
sw=1
Add(10,5)
Move if( sw, x, y)
</pre>
 
La definición de la macro en "jambo.h" es la siguiente:
 
<pre>
#defn Moveif(_X_,_Y_,_Z_) #ATOM#CMPLX;jnt(#ENDIIF);mov(_Y_);jmp(#ENDIF);%ENDIIF:;mov(_Z_);%ENDIF:
</pre>
 
La macro "COPY IF" es semejante a "MOVE IF", pero deja el valor en la memoria:
 
<pre>
sw=1
Add(10,5)
Copy if( sw, x, y) --> x guarda "15"
Prnl --> imprime "15"
</pre>
 
La macro "MOVE ON" mueve un valor desde la memoria hasta una variable, si se cumple una condición lógica; si no se cumple, el valor se retira de la memoria. Ejemplo:
 
<pre>
sw=0
Add(10,5)
Move on( sw, x)
</pre>
 
La macro "COPY ON" es semejante a "MOVE ON", pero deja el valor en la memoria, haya o no haya sido guardado en la variable. Ejemplo:
 
<pre>
sw=0
Add(10,5)
Copy on( sw, x)
Prnl
</pre>
 
La macro "SET ON" deja un valor o resultado de una expresión en memoria, si se cumple la condición:
 
<pre>
Set '100, 10, 0.05, 1.5E-5'
sw=1
Set on( sw, Add(10,5) )
Apnd Lst 'lista'
</pre>
 
La macro "SET IF" deja en memoria el resultado de una expresión o un valor en memoria, dependiendo de una expresión lógica. En el ejemplo, dejará el resultado de la suma:
 
<pre>
sw=1
Set if ( sw, Add(10,5), Sub( 10, Mul(i,2) ) )
Move to 'res'
</pre>
 
La macro "GET IF" obtiene un valor o resultado de una expresión, según una expresión lógica. Es idéntica a "SET IF", pero puede ser usada con la macro "LET":
 
<pre>
sw=1
Let ' res := Get if ( sw, Add(10,5), Sub( 10, Mul(i,2) ) ) '
</pre>
 
La macro "SWITCH" es una macro de selección múltiple, pero puede ser evaluada una expresión o valor de cualquier tipo:
 
<pre>
Switch ( expresion|valor )
Case 'valor' { ... [Exit] } --> coincide con el valor
Btwn 'v1, v2' { ... [Exit] } --> si está entre los valores "v1" y "v2"
Exact occurs 's' { ... [Exit] } --> si está contenido exactamente en el string "s"
Occurs 's' { ... [Exit] } --> si está contenido en el string "s"
On list 'l' { ... [Exit] } --> si está en el array-lista "l"
Default { ... [Exit] } --> si nada tiene sentido.
End switch
</pre>
 
Se pueden usar otras macros como evaluadores "CASE", como son las siguientes:
 
<pre>
Case not negative { ... [Exit] }
Case not zero { ... [Exit] }
Case not positive { ... [Exit] }
Case not numeric { ... [Exit] }
Case not string { ... [Exit] }
Case not array { ... [Exit] }
Case not null { ... [Exit] }
Case negative { ... [Exit] }
Case zero { ... [Exit] }
Case positive { ... [Exit] }
Case numeric { ... [Exit] }
Case string { ... [Exit] }
Case array { ... [Exit] }
Case null { ... [Exit] }
 
</pre>
 
EL "ODIADO" GOTO (pero yo lo amo):
 
La estructura "ON GOTO" se usa para saltar a una etiqueta de acuerdo a lo que encuentre en la memoria. Evalúa valores desde 1 en adelante. NOTA: si el valor de la memoria no coindice con la evaluación de "ON GOTO", queda en la memoria.
 
<pre>
EQ3:
instrucciones
Goto 'Elección de saltos'
 
...
Elección de saltos:
Ceil(Rand '3'), On goto( EQ1, EQ2, EQ3 )
Kill --> retira el valor de la memoria, si no fue consumido por "ON GOTO"
...
EQ1:
instrucciones
EQ2:
instrucciones
</pre>
 
La estructura "ON GOSUB" es idéntica a "ON GOTO", pero el control del programa retorna luego de ejecutado el bloque:
 
<pre>
Ceil(Rand '3'), On gosub( EQ1, EQ2, EQ3 )
Kill --> retira el valor de la memoria, si no fue consumido por "ON GOSUB"
...
EQ1:
instrucciones
back
EQ2:
instrucciones
back
EQ3:
instrucciones
back
</pre>
 
La estructura "ON OPTION" realiza una acción según el valor encontrado en memoria, que debe iniciar desde 1 en adelante. Si el valor memorizado no es consumido por "ON OPTION", queda en memoria y puede ser eliminado o usado por el programa:
 
<pre>
x=10
Set '3'
On option (x+=0.5, x-=0.5, x*=0.5; l=x) --> ejecuta "x*=0.5" y "l=x"
Printnl ("Resultado X= ", x)
</pre>
 
La estructura "LINK GOSUB" invoca subrutinas en secuencia. En el ejemplo, se memoriza "100", luego, se invoca a "proc1" que obtiene 200, luego invoca a "proc2" que obtiene "1000", y finalmente invoca a "proc3" que obtiene "500":
 
<pre>
Main
Set(100), Link gosub(proc1, proc2, proc3)
Prnl --> imprime el valor "500".
End
 
Subrutines
 
Define( proc1, dato )
Return ' Add(dato,100) '
 
Define ( proc2, dato )
Return ' Mul(dato,5) '
 
Define( proc3, dato )
var(dato) Div into(2)
Return
</pre>
 
Line 1,545 ⟶ 1,742:
<syntaxhighlight lang="befunge">& #v_ "0",@ zero
> "X",@ non-zero</syntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
 
Lambda calculus has no conditional structures built in, but the standard representations of booleans can be seen to implement if-then-else: true = \then. \else. then, false = \then. \else. else, which correspond to BLC programs <code>00 00 110</code> and <code>00 00 10</code>.
 
=={{header|blz}}==
Line 2,088 ⟶ 2,289:
// if condition is true var will be set to 1, else false.
int var = condition ? 1 : 2;
</syntaxhighlight>
=={{header|Curto}}==
===si-sino===
<syntaxhighlight lang="curto">( condición ) si ( sentencias si verdadero ) entonces
( condición ) si ( sentencias si verdadero ) sino ( sentencias si falso ) entonces</syntaxhighlight>
ejemplo:
<syntaxhighlight lang="curto">
: menor-que-diez ( n -- )
10 < si
." Menor que 10"
sino
." Mayor o igual a 10"
entonces ;
</syntaxhighlight>
 
Line 2,278 ⟶ 2,492:
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">i = random 10
i = randint 10
if i mod 2 = 0
print i & " is divisible by 2"
elif i mod 3 = 0
print i & " is divisible by 3"
else
print i & " is not divisible by 2 or 3"
.
.</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Efene}}==
Line 2,375 ⟶ 2,591:
x::xs = x :: force xs
[] = []</syntaxhighlight>
 
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
int i = 19
^|if–then–else|^
if i > 18
writeLine("greater than 18")
else
writeLine("less or equal to 18")
end
^|else if|^
if i == 18 do writeLine("equal to 18")
else if i < 18 do writeLine("less than 18")
else do writeLine("greater than 18")
end
^|when expression: just like iif in Visual Basic|^
writeLine(when(i > 18, "greater than 18", "less or equal to 18"))
^|hash-based conditionals|^
Map dispatch = int%fun[
18 => <|writeLine("equal to 18"),
19 => <|writeLine("yeah, it's 19")]
if dispatch.has(i) do dispatch[i]() end
</syntaxhighlight>
{{out}}
<pre>
greater than 18
greater than 18
greater than 18
yeah, it's 19
</pre>
 
=={{header|Erlang}}==
Line 2,720 ⟶ 2,967:
<syntaxhighlight lang="futhark">
if <condition> then <truebranch> else <falsebranch>
</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
FB supports conditionals similar to those in C and many other languages.
<syntaxhighlight lang="futurebasic">
local fn DoIt
long A = 7
if A > 0 then print "A is a positive number" else print "A is a negative number"
long B = -10
if B > 0
print "B is a positive number"
else
print "B is a negative number"
end if
long C = 99
select (C)
case C < 0
print "C is a negative number"
case C = 0
print "C is zero"
case C > 0
print "C is a positive number"
case else
print "C is unknown"
end select
CFStringRef suitName, suitSymbol
suitSymbol = @"S"
select (suitSymbol)
case @"C": suitName = @"Clubs"
case @"D": suitName = @"Diamonds"
case @"H": suitName = @"Hearts"
case @"S": suitName = @"Spades"
case else : suitName = @"Unknown"
end select
print suitName
end fn
 
fn Doit
 
HandleEvents
</syntaxhighlight>
 
Line 2,731 ⟶ 3,022:
<statements>
fi;</syntaxhighlight>
 
 
=={{header|Go}}==
Line 2,828 ⟶ 3,120:
}
fmt.Println("I'm off!")</syntaxhighlight>
 
=={{header|Grain}}==
===If statements===
In Grain, if statements are expressions, meaning they can be used for variable assignments.
If they are used as an expression, the return value must be of the same type, meaning an else clause is always required.
If an if statement has nothing returned as the body (the body is of the Void type), the else clause can be omitted.
<syntaxhighlight lang="grain">
let x = if (1 < 2) {
":)"
} else { // The else clause is required here as x is a string
":("
}
 
if (2 > 3) {
print("This should never execute.")
} // We can omit the else clause here
 
// We use else if for chaining
if (1 > 2) {
print("1 is less than 2")
} else if (2 == 3) {
print("2 is 3")
} else {
print("This should always execute.")
}
</syntaxhighlight>
 
===Pattern matching===
Pattern matching in Grain is like a switch-statement with superpowers. Each case of a match defines the pattern that the data could fall into.
<syntaxhighlight lang="grain">
// A match statement more like the traditional switch statement
// often seen in other languages.
enum PizzaTopping { Cheese, Pepperoni, Peppers, Pineapple }
 
let topping = Peppers
 
match (topping) {
Cheese => print("Would it really be pizza without it?"),
Pepperoni => print("An instant classic."),
Peppers => {
// We can use a block for more expressions.
print("For those who like to spice things up.")
},
Pineapple => print("You do you.")
}
</syntaxhighlight>
As well as a traditional switch statement, we can match on the shape of the data.
If we keep with the pizza theme, this looks a bit like this.
<syntaxhighlight lang="grain">
enum Topping { Cheese, Pepperoni, Peppers, Pineapple }
enum Menu { Pizza(Topping), Calzone(Topping) }
 
let item = Calzone(Peppers)
 
match (item) {
Calzone(topping) => {
if (checkSpecials(topping)) {
print("These are half off this week.")
} else {
print("No current specials.")
}
},
_ => print("No current specials.")
}
</syntaxhighlight>
 
=={{header|Harbour}}==
Line 3,103 ⟶ 3,460:
=={{header|J}}==
See [[Conditional Structures/J]]
 
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn main() {
let a = 5
let b = 3
 
// If/else/else-if
if a > b {
println("a > b")
} else if a < b {
println("a < b")
} else {
println("a = b")
}
 
// Match
match a {
(..5) => {
println("a < 5")
}
5 => {
println("a == 5")
}
else => {
println("a > 5")
}
}
 
// Or equivalently
println(match a {
(..5) => "a < 5"
5 => "a == 5"
else => "a > 5"
})
 
// Hash based
let primality = [
1: false
2: false
3: true
4: false
5: true
6: false
]
let a_is_prime = primality[a]
println("a_is_prime = {}", a_is_prime)
}
</syntaxhighlight>
 
=={{header|Java}}==
===if-then-else===
<syntaxhighlight lang="java">if (s.equals("Hello World")) {
{
foo();
} else if (s.equals("Bye World"))
}
bar(); // braces optional for one-liners
else if(s.equals("Bye World"))
else {
bar();//{}'s optional for one-liners
else
{
deusEx();
}</syntaxhighlight>
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
<syntaxhighlight lang="java">if (obj != null && obj.foo()) {
aMethod();
}</syntaxhighlight>
<tt>obj.foo()</tt> will not be executed if <tt>obj != null</tt> returns false. It is possible to have conditionals without short circuit evaluation using the <tt>&</tt> and <tt>|</tt> operators (from [[Bitwise operations]]). So in this conditional:
<syntaxhighlight lang="java">if (obj != null & obj.foo()) {
aMethod();
}</syntaxhighlight>
You will get a null pointer exception if <tt>obj</tt> is null.
===ternary===
 
<syntaxhighlight lang="java">s.equals("Hello World") ? foo() : bar();</syntaxhighlight>
The ternary operator is an expression, and is most often used as such:
<syntaxhighlight lang="java">Object newValue = s.equals("Hello World") ? a : b;</syntaxhighlight>
 
===switch===
This structure will only work if the code being switched on evaluates to an integer or character. There is no switching on Objects<code>Object</code>s (except for Java 17 and higher), <code>long</code>s, or floating-point types in Java (except for <code>String</code>s and enum types in Java 7 and higher).
<syntaxhighlight lang="java">switch (c) {
case 'a':
foo();
break;
case 'b':
bar();
default:
foobar();
}</syntaxhighlight>
This particular example can show the "fallthrough" behavior of a switch statement. If c is the character b, then bar() and foobar() will both be called. If c is the character a, only foo() will be called because of the break statement at the end of that case.
 
Also, the switch statement can be easily translated into an if-else if-else statement. The example above is equivalent to:
<syntaxhighlight lang="java">if (c == 'a') {
foo();
} else if (c == 'b') {
bar();
foobar();
} else {
foobar();
}</syntaxhighlight>
Cases without breaks at the end require duplication of code for all cases underneath them until a break is found (like the else if block shown here).
 
===switch expressions===
{{works with|Java|14+}}
Switch statements can be expressions. They must be exhaustive, and return a value with the <tt>yield</tt> keyword.
<syntaxhighlight lang=“java”>int x = switch (c) {
case 'a':
foo();
yield 1;
case 'b':
bar();
default:
foobar();
yield 0;
}</syntaxhighlight>
 
There is also a new syntax, available for both statements and expressions, that does not use fallthrough:
<syntaxhighlight lang=“java”>int y = switch (c) {
case '1', '2' -> 1 // multiple cases can be on one line
default -> { // use a block for multiple statements
foobar();
yield 0;
}
}</syntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,468 ⟶ 3,895:
 
=={{header|langur}}==
If and givenswitch expressions always produce a value, even if it's nothing (null).
 
In the shortened forms, you dispense with the keywords (except the first one).
Line 3,474 ⟶ 3,901:
===if expressions===
If expressions are scoped per section.
<syntaxhighlight lang="langur">#if using.x the== fact0 that submatch() returns an empty array for no match ...{
# ... and that a decoupling assignment returns a Boolean...
 
if val .alias, .name = submatch($re/^(\.idregex;)\\s*;\\s*(\.idregex;)/, .row) {
# success (2 or more values in array returned from submatch function)
# use .alias and .name here
...
} else if .x > 0 {
Line 3,488 ⟶ 3,910:
...
}</syntaxhighlight>
 
Prior to langur 0.10, you would use parentheses around the declared variable names (.alias, .name).
 
===shortened form if expression===
Line 3,498 ⟶ 3,918:
<syntaxhighlight lang="langur">if(.x > .y: ...; .x < .y: ...; /* else */ ...)</syntaxhighlight>
 
===ifsimple statementsif===
LangurSimple 0.7.1 added "if statements,"expressions usinguse 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>
 
===givenswitch expressions===
GivenSwitch expressions are highly flexible, and it is not all covered here. See langurlang.org for details.
 
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].
Given expressions are scoped per section. Also, test expressions (such as the .x, .y, .z list below) may contain declarations which are scoped to the entire expression.
 
<syntaxhighlight lang="langur">givenswitch .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
Line 3,517 ⟶ 3,954:
}</syntaxhighlight>
 
As of 0.7, complexComplex test expressions are evaluated once, then compared against conditions.
 
The default logical operator between multiple conditions is "and" (even when there is a single test expression). You can specify another operator after the "case" keyword, using something like "case or".
 
<syntaxhighlight lang="langur">given .x, .y, != .z {
case 7 <, 14, 21: ...
# 7 < .x and .y == 14 and 21 != .z
 
case or > 100, _, re/abc/: ...
# .x > 100 or matching(re/abc/, .z)
 
case ; .a > .b: ...
# .a > .b
 
case _, _, == 7; xor .a <= .b: ...
# .z == 7 xor .a <= .b
 
default: ...
}</syntaxhighlight>
 
===implicit fallthrough===
If a block of a givenswitch has any statements, there is no implicit fallthrough. A case with an empty block after it creates an implicit fallthrough.
<syntaxhighlight lang="langur">givenswitch .x {
case true:
# implicit fallthrough
Line 3,548 ⟶ 3,967:
 
===explicit fallthrough from anywhere===
A fallthrough statement is allowed anywhere within a givenswitch 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">given .x {
<syntaxhighlight lang="langur">switch .x {
case true:
if .y > 100 {
Line 3,559 ⟶ 3,979:
}</syntaxhighlight>
 
===shortened form givenswitch===
A shortened form given 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">givenswitch(.x, .y, .z;
true: ... ; # allany are equal to true
_, >= .z: ...; # .y >= .z
... ) # default</syntaxhighlight>
Line 4,839 ⟶ 5,259:
 
=={{header|Ol}}==
if-then, the simplest conditional `if` primitive.
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4) (print "if-then: equal"))
(if (= (* 2 2) 6) (print "if-then: non equal"))
(if (= (* 2 2) 6)
(print "if-then: should not be printed"))
; ==> if-then: equal
</syntaxhighlight>
 
if-then-else, the full conditional '`if'` primitive.
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4) (print "if-then-else: equal") (print "if-then-else: non equal"))
(if (= (* 2 2) 6) (print "if-then-else: non equal") (print "if-then-else: i don't know"))
(print "if-then-else: non equal"))
; ==> if-then-else: equal
 
; ==> if-then-else: i don't know
(if (= (* 2 2) 6)
(print "if-then-else: equal")
(print "if-then-else: non equal"))
; ==> if-then-else: non equal
</syntaxhighlight>
 
when and unless, the oppositesimplification forof '`if'.` without `begin`
<syntaxhighlight lang="scheme">
(unlesswhen (= (* 2 2) 4) (print "unless: non equal"))
(unless (= (* 2 2) 6) (print "unlesswhen: i..just don'tdo knowsomething.."))
(unless (= (* 2 2) 4) (print "unless: non equal") (print "unlesswhen: equal"))
; ==> when: ..just do something..
(unless (= (* 2 2) 6) (print "unless: i don't know") (print "unless: non equal"))
; ==> unlesswhen: i don't knowequal
 
; ==> unless: equal
(unless (= (* 2 2) 6)
; ==> unless: i don't know
(print "unless: ..just do something..")
(print "unless: not equal"))
; ==> unless: ..just do something..
; ==> unless: not equal
</syntaxhighlight>
 
if-then-else, extended conditional `if` primitive.
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4)
(print "if-then-else*: equal")
else
(print "if-then-else*: ..just do something..")
(print "if-then-else*: non equal"))
; ==> if-then-else*: equal
 
(if (= (* 2 2) 4)
then
(print "if-then-else*: ..just do something..")
(print "if-then-else*: equal")
else
(print "if-then-else*: ..just do something..")
(print "if-then-else*: non equal"))
; ==> if-then-else*: ..just do something..
; ==> if-then-else*: equal
 
(if (= (* 2 2) 4) ; same as `when`
then
(print "if-then-else*: ..just do something..")
(print "if-then-else*: equal"))
; ==> if-then-else*: ..just do something..
; ==> if-then-else*: equal
</syntaxhighlight>
 
Line 4,868 ⟶ 5,326:
<syntaxhighlight lang="scheme">
(case (* 2 2)
(3 ; exact number
(print "case: 3"))
(4 ; exact number
(print "case: 4"))
((5 6 7) ; list of numbers
(print "case: 5 or 6 or 7"))
(else
(print "case: i don't know")))
; ==> case: 4
</syntaxhighlight>
 
; extended case with usable else
additionally, case can select vectors with variables filling
(case (* 2 2)
<syntaxhighlight lang="scheme">
(3 ; exact number
(case (vector 'selector 1 2 3)
(print "case: 3"))
(else => (lambda (num)
(print "case: real value is " num))))
; ==> case: real value is 4
 
(case (* 2 2)
(3 ; exact number
(print "case: 3"))
(else is num
(print "case: real value is " num)))
; ==> case: real value is 4
 
; extended case with vectors
(case ['selector 1 2 3]
(['case1 x y]
(print "case: case1 " x ", " y))
Line 4,888 ⟶ 5,359:
(else
(print "case: i don't know")))
; ==> tuple-case: selector 1, 2, 3
</syntaxhighlight>
 
Line 5,573 ⟶ 6,044:
...
END;</syntaxhighlight>
 
=={{header|Plain English}}==
Plain English only has one kind of conditional, called a "conditional".
<syntaxhighlight lang="text">If [a decider], [do something]; [do another thing].</syntaxhighlight>
The first parameter is a decider that returns yes or no. If the result was yes, all the other statements on the same line as the conditional will execute. Otherwise, execution continues immediately to the next line.
 
If the decider uses a negative word, the negative word is removed, the decider is done normally, and the result is reversed.
 
Conditionals may not go beyond 1 SLOC. Conditionals cannot be nested.
 
=={{header|Pop11}}==
Line 6,093 ⟶ 6,573:
 
(<code>]'[</code>, pronounced "meta-literal" grants the property of <code>'</code> (pronounced "literal", <code>'</code> places the item following it on the stack and unconditionally branches over it) to the enclosing nest.)
 
See [[Flow-control structures#Quackery]] for a deeper dive into Quackery control flow.
 
=={{header|R}}==
Line 6,430 ⟶ 6,912:
}}
</syntaxhighlight>
 
=={{header|RPL}}==
'''IF..THEN'''
'''IF''' <instruction(s)> '''THEN''' <instruction(s)> '''END'''
'''IF..THEN..ELSE'''
'''IF''' <instruction(s)> '''THEN''' <instruction(s)> '''ELSE''' <instruction(s)> '''END'''
Instructions between <code>IF</code> and <code>THEN</code> are not mandatory, but recommended for lisibility. The interpreter considers <code>IF</code> as a null word and performs branching when meeting the word <code>THEN</code>: if stack level 1 is not equal to zero, the instructions between <code>THEN</code> and <code>END</code> will be executed.
 
<code>IFT</code> and <code>IFTE</code> are stack-based conditonal structures. <code>IFT</code> evaluates the content of stack level 1 only if the content of stack level 2 is not zero, otherwise it is dropped. <code>IFTE</code> evaluates the content of stack level 1 if the content of stack level 2 is zero, otherwise if evaluates the content of stack level 2.
 
'''CASE..END'''
'''CASE'''
<instruction(s)> '''THEN''' <instruction(s)> '''END'''
<instruction(s)> '''THEN''' <instruction(s)> '''END'''
<span style="color:grey">@ as many branches as needed</span>
<instruction(s)> <span style="color:grey">@ default branch (optional)</span>
'''END'''
 
=={{header|Ruby}}==
Line 6,903 ⟶ 7,402:
(else 'zero))</syntaxhighlight>
 
=={{header|SmallBASIC}}==
 
===if===
 
<syntaxhighlight lang="basic">
IF foo == 1
PRINT "one"
ELSEIF foo == 2
PRINT "two"
ELSE
PRINT "something else"
ENDIF
</syntaxhighlight>
 
===Inline if===
<syntaxhighlight lang="basic">ans = iff(x <= 5, 0, 10)</syntaxhighlight>
 
===select===
<syntaxhighlight lang="basic">
select case x
case 12
print "x is 12"
case 13,14,15
print "x is 13,14,or 15"
case iff(x <= 4, x, x + 1)
print "x <= 4"
case else
print "x is not <=4,12,13,14,15"
end select
</syntaxhighlight>
 
=={{header|Smalltalk}}==
Line 7,336 ⟶ 7,862:
 
<syntaxhighlight lang="tqs">%formatted = %str @ ((getSubStr(%str,strLen(%str) - 1,1) $= "s") ? "'" : "'s");</syntaxhighlight>
 
 
=={{header|Transd}}==
 
Transd has as an universal conditional expression - the '''if-elsif-else''' operator. Also, the conditional evaluation
is achieved through logical functions.
 
<syntaxhighlight lang="Scheme">#lang transd
 
MainModule: {
_start: (λ locals: b 1 c 0
(textout (if b "OK" else "NO") "\n")
 
// switch/case emulation
 
(textout (* 5
(if (== b 0) 2
elsif (== b 1) 5
else 6)) "\n")
 
// example of using 'or' as a conditional construct
 
(or (!= c 0) (textout "c is 0"))
)
}</syntaxhighlight>
{{out}}
<pre>
OK
25
c is 0
</pre>
 
=={{header|Trith}}==
Line 7,493 ⟶ 8,050:
There are optional <code>elif</code> (else if) and <code>else</code> clauses.
 
<syntaxhighlight lang="sh">if test 4 -ge 6; then
then echo '4 is greater than or equal to 6'
elif test 4 -lt 6; then
then echo '4 is less than 6'
else echo '4 compares not to 6'
else
echo '4 compares not to 6'
fi</syntaxhighlight>
 
Line 7,559 ⟶ 8,115:
else
x * fac (Nat.drop x 1)</syntaxhighlight>
 
=={{header|Ursalang}}==
===if…then…else===
Ursalang has a single conditional construct, the familiar `if…then…else`.<syntaxhighlight lang="ursalang">
if energyLevel > 9000 { "That's impossible!!!" } else { "Ok, I guess" }
</syntaxhighlight>As in most C-like languages, conditionals can be chained:<syntaxhighlight>
if color == "red" { "aaaaaah!" }
else if color == "blue" { "oooooh!" }
else { "eeeeeeee!" }
</syntaxhighlight>
 
=={{header|V}}==
Line 7,988 ⟶ 8,554:
<syntaxhighlight lang="vbnet">Dim result As String = If("pants" = "glasses", "passed", "failed") ' type is inferred</syntaxhighlight>
 
=={{header|V (Vlang)}}==
If and match are the general purpose conditional structures in V (Vlang), although the language certainly contains other conditional elements.
===If===
Simplest usage is,
<syntaxhighlight lang="v (vlang)">if boolean_expression {
statements
}</syntaxhighlight>
The braces are required, even around a single statement.
<syntaxhighlight lang="v (vlang)">if boolean_expression {
statements
} else {
Line 8,003 ⟶ 8,569:
}</syntaxhighlight>
Braces are required around else clauses, as above, unless the statement of the else clause is another if statement. In this case the statements are chained like this,
<syntaxhighlight lang="v (vlang)">if boolean_expression1 {
statements
} else if boolean_expression2 {
Line 8,012 ⟶ 8,578:
===Match===
Simple usage is,
<syntaxhighlight lang="v (vlang)">match true {
boolean_expression1 {
statements
Line 8,029 ⟶ 8,595:
 
Match can also switch on the value of an expression, as in,
<syntaxhighlight lang="v (vlang)">switch expression_of_any_type {
value1 {
statements
Line 8,085 ⟶ 8,651:
=={{header|Wren}}==
The ''if/else'' statement and the ''ternary operator (?:)'' are Wren's basic conditional structures though it can be argued that the ''&&'' and ''||'' operators, which do short-circuit evaluation, should be included under this heading as well.
<syntaxhighlight lang="ecmascriptwren">for (b in [true, false]) {
if (b) {
System.print(true)
5

edits