Conditional structures: Difference between revisions

m
→‎case without a default: the error discussed isn’t syntactic
(add Zig example)
m (→‎case without a default: the error discussed isn’t syntactic)
 
(45 intermediate revisions by 33 users not shown)
Line 2:
{{Control Structures}}
[[Category:Simple]]
[[Category:Flow control]]
 
;Task:
Line 16 ⟶ 17:
=={{header|11l}}==
===if-else===
<langsyntaxhighlight lang="11l">I x == 0
foo()
E I x == 1
bar()
E
baz()</langsyntaxhighlight>
 
===switch===
<langsyntaxhighlight lang="11l">S x
0
foo()
Line 30 ⟶ 31:
bar()
E
baz()</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
Here are the branch mnemonic opcodes:
<langsyntaxhighlight lang="360asm">* Unconditional Branch or No Branch:
B label Unconditional
BR Rx "
Line 81 ⟶ 82:
BNMR Rx "
BNZ label Branch if Not Zero
BNZR Rx "</langsyntaxhighlight>
The ASM (Assembler Structured Macros) toolkit brings structures to IBM assembler 360.
<langsyntaxhighlight lang="360asm"> expression:
opcode,op1,rel,op2
opcode,op1,rel,op2,OR,opcode,op1,rel,op2
Line 155 ⟶ 156:
CASE 7 case 7
LA R5,4 r5=4
ENDCASE end select</langsyntaxhighlight>
 
=={{header|6502 Assembly}}==
Line 161 ⟶ 162:
6502 Assembly has 8 conditional branch instructions; each instruction will test the appropriate flag and condition and jump between -128 and 127 bytes.
To understand these conditional instructions, it is helpful to remember that the comparison instructions (CMP, CPX, CPY) set the flags as if a subtraction had occurred:
<langsyntaxhighlight lang="6502asm"> LDA #10
CMP #11</langsyntaxhighlight>
Following these instructions, the accumulator will still hold 10 but the flags are set as if you had instructed the processor to perform 10 - 11.
The result is -1, so the sign flag will be set, the zero flag will be cleared, the overflow flag will be cleared, and the carry flag will be set.
<langsyntaxhighlight lang="6502asm"> BNE ;Branch on Not Equal - branch when the zero flag is set
BEQ ;Branch on EQual - branch when the zero flag is set.
;The zero flag is set when the result of an operation is zero
Line 184 ⟶ 185:
;a subtraction produced a borrow and cleared if an addition/subtraction
;does not produce a carry/borrow. The carry flag also holds bits
;after shifts and rotates.</langsyntaxhighlight>
In the following example, the branch will be taken if memory location Variable holds 200:
<langsyntaxhighlight lang="6502asm"> LDA #200
CMP Variable
BEQ #3 ;if equal, skip ahead 3 bytes...
CLC ;if unequal, continue executing instructions
ADC #1
STA OtherVariable ; ...to here.</langsyntaxhighlight>
Because you don't have to perform a comparison to set the flags, you can perform very fast checks in iterative loops:
<langsyntaxhighlight lang="6502asm"> LDX #100
Loop: ...do something
DEX
BNE Loop</langsyntaxhighlight>
This code will loop until X is zero.
Most assemblers will figure out the correct offset for you if you use a label in place of the offset after a branch instruction, as in the above example.
Line 203 ⟶ 204:
A jump table is a list of subroutine addresses, which can be indexed like any other array. The 6502 has no indirect call command, but it can be created in software using an indexed jump table. One method of doing this is spoofing a return address and using the return from subroutine command to "return" to the desired subroutine.
 
<langsyntaxhighlight lang="6502asm">ReturnTable:
dw foo-1 ;each is a label to a section of code that ends in an RTS
dw bar-1
Line 223 ⟶ 224:
; If done properly, return spoofing will not corrupt the stack.
 
RTS ;this "RTS" acts as a JMP to the address we just put on the stack.</langsyntaxhighlight>
=={{header|68000 Assembly}}==
Like [[6502 Assembly]], 68000 Assembly has several different condition states the CPU can use to branch. As is typical with assembly languages, branching code is less straightforward than on high-level languages. There is no "if" statement per se; the correct branch to use depends more so on the expression being evaluated.
Line 231 ⟶ 232:
===CMP===
The most commonly used comparator is <code>CMP</code>. It can operate at byte, word, or long length. Anything outside of the "range" of its size parameter is ignored.
<langsyntaxhighlight lang="68000devpac">MOVE.L #$FFFFFF00,D0
CMP.B #0,D0 ;equals zero, so zero flag is set.
CMP.W #0,D0 ;doesn't equals zero, so zero flag is clear.</langsyntaxhighlight>
 
Other than its size parameter, <code>CMP</code> works very similar to [[6502 Assembly]]. It returns both a test for equality and a size comparison (i.e. which number is greater than the other.) This chart from [http://www.easy68k.com/paulrsm/doc/trick68k.htm 68000 Tricks and Traps] sums it up nicely. If you use <code>CMP D0,D1</code> at any data size, this is what you get:
Line 249 ⟶ 250:
===Bit Testing===
Individual bits can be tested with <code>BTST</code>, <code>BSET</code>, <code>BCLR</code>, and <code>BCHG</code>. The <code>BTST</code> command takes a bit as its left operand and the value being tested in the right (either a data register, address register with or without parentheses, or memory address).
<langsyntaxhighlight lang="68000devpac">BTST #7,D0 ;test bit 7 of D0, i.e. the leftmost bit in the rightmost byte.
BNE goHere ;if that bit is 1, branch to "goHere"
BEQ goThere ;if that bit is 0, branch to "goThere"</langsyntaxhighlight>
 
<code>BSET</code>, <code>BCLR</code>, and <code>BCHG</code> are similar, in that they also allow you to branch based on the value of the bit being tested. However, they also alter the bit in the destination that was tested, AFTER the test. The new state of that bit is not reflected in the test results. Branching occurs as if you used <code>BTST</code> instead. <code>BSET</code> makes the bit in the destination 1, <code>BCLR</code>makes it zero, and <code>BCHG</code> flips it.
Line 260 ⟶ 261:
These concepts can be emulated in assembly but it's a bit tricky for beginners to understand. The branch condition isn't always what you would expect. Sometimes it is reversed depending on what is easier to check. This is a common way to have an <code>IF condition==true THEN do something ELSE do nothing</code> style of statement. The code checks if <code>D0 == 3</code> and if it does, adds 7. If <code>D0 != 3</code>, execution just continues as normal.
 
<langsyntaxhighlight lang="68000devpac">CMP.L #3,D0 ;this works with any size operands, not just L.
BNE doNothing
ADD.L #7,D0
doNothing:
;rest of program</langsyntaxhighlight>
 
Rather than branch to a different section of code if <code>D0 == 3</code>, the program branched if it <b>DIDN'T</b> equal 3, skipping the add 7.
Line 272 ⟶ 273:
There is no built-in way to "default" if none of the expected cases match. A bounds check will have to be programmed in manually. Most of the time when writing a return spoof the programmer already knows what the maximum possible cases will be.
 
<langsyntaxhighlight lang="68000devpac">SwitchCase:
DC.L foo,bar,baz,default ;case 0, case 1, case 2, case 3. (Case 0,1,2 are the "valid" cases.)
; D0 is the case selector variable (byte-sized)
Line 305 ⟶ 306:
 
default:
rts</langsyntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program condstr64.s */
Line 530 ⟶ 531:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
INT i
 
Line 546 ⟶ 547:
FI
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Conditional_structures.png Screenshot from Atari 8-bit computer]
Line 560 ⟶ 561:
=={{header|Ada}}==
===if-then-else===
<langsyntaxhighlight lang="ada">type Restricted is range 1..10;
My_Var : Restricted;
 
Line 569 ⟶ 570:
else
-- do something
end if;</langsyntaxhighlight>
===conditional expressions===
Ada 2012 introduces conditional expressions, which are allowed anywhere an expression is allowed (e.g.: in a numeric literal, aggregate, etc.). A conditional expression can either be an if expression or case expression. Conditional expressions must be surrounded by parentheses.
====if expression====
<langsyntaxhighlight lang="ada">type Operation is (Add, Subtract, Multiply, Divide);
Op : Operation;
Result : Integer;
Line 585 ⟶ 586:
elsif Op = Divide then
A / B
);</langsyntaxhighlight>
====case expressions====
Using the same example above, we assume that the <lang ada>''Operation</lang>'', <lang ada>''Op</lang>'', and <lang ada>''Result</lang>'' variables are declared. A case expression over the enumeration of operations might look like:
<langsyntaxhighlight lang="ada">Result := (case Op is
Add => A + B,
Subtract => A - B,
Line 594 ⟶ 595:
Divide => A / B
);
</syntaxhighlight>
</lang>
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...</langsyntaxhighlight>). 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===
<langsyntaxhighlight lang="ada">type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
Today : Days;
 
Line 609 ⟶ 611:
when others =>
Accumulate_Sales;
end case;</langsyntaxhighlight>
 
===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:
 
<langsyntaxhighlight lang="ada">case Today is
when Monday =>
Compute_Starting_Balance;
Line 623 ⟶ 625:
Accumulate_Sales;
-- ignore Saturday and Sunday
end case;</langsyntaxhighlight>
 
The syntactically correct version:
 
<langsyntaxhighlight lang="ada">case Today is
when Saturday | Sunday =>
null; -- don't do anything, if Today is Saturday or Sunday
Line 636 ⟶ 638:
when Tuesday .. Thursday =>
Accumulate_Sales;
end case;</langsyntaxhighlight>
 
===select===
Line 643 ⟶ 645:
 
====Conditional Accept====
<langsyntaxhighlight lang="ada">select
accept first_entry;
-- do something
Line 649 ⟶ 651:
-- do something
or terminate;
end select;</langsyntaxhighlight>
 
====Conditional entry call====
A selective entry call provides a way to time-out an entry call.
Without the time-out the calling task will suspend until the entry call is accepted.
<langsyntaxhighlight lang="ada">select
My_Task.Start;
or
delay Timeout_Period;
end select;</langsyntaxhighlight>
The entry Start on the task My_Task will be called.
If My_Task accepts the entry call before the timer expires the timer is canceled. If the timeout expires before the entry call is accepted the entry call is canceled.
Line 664 ⟶ 666:
=={{header|Aikido}}==
===Conditional Expressions===
<langsyntaxhighlight lang="aikido">
var x = loggedin ? sessionid : -1
 
</syntaxhighlight>
</lang>
 
===if..elif..else===
<langsyntaxhighlight lang="aikido">
if (value > 40) {
println ("OK")
Line 678 ⟶ 680:
println ("RETRY")
}
</syntaxhighlight>
</lang>
 
===switch===
<langsyntaxhighlight lang="aikido">
switch (arg) {
case "-d":
Line 707 ⟶ 709:
println ("RETRY")
}
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
Line 713 ⟶ 715:
===If-elif-else===
 
<langsyntaxhighlight lang="aime">if (c1) {
// first condition is true...
} elif (c2) {
Line 721 ⟶ 723:
} else {
// none was true...
}</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
Line 734 ⟶ 736:
'''if''' X=Y '''then''' K:=I
An example:
<langsyntaxhighlight lang="algol60"> 'IF' I=1 'THEN' OUTINTEGER(1,I);
 
'IF' I<J 'THEN' OUTSTRING(1,'(' : I<J')')
Line 746 ⟶ 748:
OUTSTRING(1,'(' J=')');
OUTINTEGER(1,J)
'END'</langsyntaxhighlight>
Algol 60 has also a switch structure:
declaration::= '''switch''' switch:=list_of labels
statement::= '''goto''' switch[expression]
An example:
<langsyntaxhighlight lang="algol60"> 'SWITCH' TARGET:=L1,L2,L3;
...
'GOTO' TARGET(/J/);
L1: OUTSTRING(1,'('AA')');
L2: OUTSTRING(1,'('BB')');
L3: OUTSTRING(1,'('CC')');</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 762 ⟶ 764:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
integer a, b, c;
 
Line 793 ⟶ 795:
write( case c - a of ( "one", "two", "three", "four" ) )
 
end.</langsyntaxhighlight>
{{out}}
<pre>
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 810 ⟶ 1,007:
The second and third arguments should be blocks (aka anonymous functions or thunks).
 
<langsyntaxhighlight lang="ambienttalk">
if: condition then: {
// condition is true...
Line 816 ⟶ 1,013:
// condition is false...
}
</syntaxhighlight>
</lang>
 
===IfTrue/IfFalse===
Line 822 ⟶ 1,019:
One can also send a message to the boolean objects true and false:
 
<langsyntaxhighlight lang="ambienttalk">
condition.ifTrue: { /* condition is true... */ } ifFalse: { /* condition is false... */ }
</syntaxhighlight>
</lang>
 
=={{header|AmigaE}}==
'''IF-THEN-ELSE'''
<langsyntaxhighlight lang="amigae">IF condition
-> if condition is true...
ELSEIF condition2
Line 834 ⟶ 1,031:
ELSE
-> if all other conditions are not true...
ENDIF</langsyntaxhighlight>
 
or on one single line:
 
<syntaxhighlight lang ="amigae">IF condition THEN statement</langsyntaxhighlight>
 
'''Ternary IF THEN ELSE'''
 
The IF-THEN-ELSE can be used like ternary operator (?: in C)
<langsyntaxhighlight lang="amigae">DEF c
c := IF condition THEN 78 ELSE 19</langsyntaxhighlight>
 
'''SELECT-CASE'''
 
<langsyntaxhighlight lang="amigae">SELECT var
CASE n1
-> code
Line 855 ⟶ 1,052:
DEFAULT
-> no one of the previous case...
ENDSELECT</langsyntaxhighlight>
 
Another version allows for ranges:
 
<langsyntaxhighlight lang="amigae">SELECT max_possible_value OF var
CASE n1
-> code
Line 868 ⟶ 1,065:
DEFAULT
-> none of previous ones
ENDSELECT</langsyntaxhighlight>
 
The biggest among n1, n2 and so on, must be not bigger than max_possible_value.
Line 874 ⟶ 1,071:
=={{header|Apex}}==
===if-then-else===
<langsyntaxhighlight lang="java">if (s == 'Hello World') {
foo();
} else if (s == 'Bye World') {
Line 880 ⟶ 1,077:
} else {
deusEx();
}</langsyntaxhighlight>
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
<langsyntaxhighlight lang="java">if(obj != null && obj.foo()){
aMethod();
}</langsyntaxhighlight>
<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:
<langsyntaxhighlight lang="java">if(obj != null & obj.foo()){
aMethod();
}</langsyntaxhighlight>
You will get a null pointer exception if obj is null.
===ternary===
 
<langsyntaxhighlight lang="java">s == 'Hello World' ? foo() : bar();</langsyntaxhighlight>
 
===switch===
Line 899 ⟶ 1,096:
=={{header|AppleScript}}==
===if-then-else===
<langsyntaxhighlight lang="applescript">if myVar is "ok" then return true
 
set i to 0
Line 908 ⟶ 1,105:
else
return "odd"
end if</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 1,063 ⟶ 1,260:
bx lr /* return */
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
===if?-else===
 
<langsyntaxhighlight lang="rebol">num: 2
 
if? num=2 [
Line 1,075 ⟶ 1,272:
else [
print "something went wrong..."
]</langsyntaxhighlight>
 
{{out}}
Line 1,083 ⟶ 1,280:
===case-when?===
 
<langsyntaxhighlight lang="rebol">loop 1..5 'num [
case [num]
when? [<2] -> print [num ": it's less than 2"]
Line 1,090 ⟶ 1,287:
else -> print [num ": the number is too big"]
]
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,101 ⟶ 1,298:
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">if x == 0:
foo()
elif x == 1:
Line 1,116 ⟶ 1,313:
_ => qux()
 
(a) ? b : c</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
 
===if, else if, else===
<syntaxhighlight lang="autohotkey">x = 1
<lang AutoHotkey>x = 1
If x
MsgBox, x is %x%
Line 1,127 ⟶ 1,324:
MsgBox, x is %x%
Else
MsgBox, x is %x%</langsyntaxhighlight>
 
===ternary if===
<syntaxhighlight lang="autohotkey">x = 2
<lang AutoHotkey>x = 2
y = 1
var := x > y ? 2 : 3
MsgBox, % var</langsyntaxhighlight>
 
===while (looping if)===
<langsyntaxhighlight AutoHotkeylang="autohotkey">While (A_Index < 3) {
MsgBox, %A_Index% is less than 3
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
===If, ElseIf, Else===
<langsyntaxhighlight AutoItlang="autoit">If <expression> Then
statements
...
Line 1,152 ⟶ 1,349:
...
EndIf
</syntaxhighlight>
</lang>
===Select Case===
<langsyntaxhighlight AutoItlang="autoit">Select
Case <expression>
statement1
Line 1,165 ⟶ 1,362:
...]
EndSelect
</syntaxhighlight>
</lang>
===Switch Case===
<langsyntaxhighlight AutoItlang="autoit">Switch <expression>
Case <value> [To <value>] [,<value> [To <value>] ...]
statement1
Line 1,178 ⟶ 1,375:
...]
EndSwitch
</syntaxhighlight>
</lang>
--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 15:39, 13 November 2013 (UTC)
 
=={{header|Avail}}==
===If-Then-Else===
<langsyntaxhighlight Availlang="avail">If year = 1999 then [Print: "Party!";];
 
If someNumber > 5 then [Print: "Too high!";] else [Print: "Adequate amount.";];
Line 1,191 ⟶ 1,388:
else [score := 45;];
 
Unless char = ¢X then [Print: "character was not an x";];</langsyntaxhighlight>
 
===Ternary===
The basic control structures in Avail can be used as expressions by using blocks with a return value. By tradition this distinction is noted by using a lowercase first character.
<langsyntaxhighlight Availlang="avail">Print: if result = 13 then ["unlucky"] else ["safe"];</langsyntaxhighlight>
 
=={{header|AWK}}==
Conditionals in awk are modelled after C:
<langsyntaxhighlight lang="awk">if(i<0) i=0; else i=42</langsyntaxhighlight>
For a branch with more than a single statement, this needs braces:
<langsyntaxhighlight lang="awk">
if(i<0) {
i=0; j=1
} else {
i=42; j=2
}</langsyntaxhighlight>
There is also the ternary conditional:
<langsyntaxhighlight lang="awk">i=(i<0? 0: 42)</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 1,215 ⟶ 1,412:
 
===Simple===
<langsyntaxhighlight lang="axe">If 1
YEP()
End</langsyntaxhighlight>
 
===Inverse If===
<langsyntaxhighlight lang="axe">!If 1
NOPE()
End</langsyntaxhighlight>
 
===If-Else===
<langsyntaxhighlight lang="axe">If 1
YEP()
Else
NOPE()
End</langsyntaxhighlight>
 
Axe has no support for switch-like statements. If-ElseIf-Else structures are required to achieve the same goal.
 
===If-ElseIf-Else===
<langsyntaxhighlight lang="axe">If 1=0
NOPE()
ElseIf 1=1
Line 1,240 ⟶ 1,437:
Else
NOPE()
End</langsyntaxhighlight>
 
===If-InverseElseIf-Else===
<langsyntaxhighlight lang="axe">If 1=0
NOPE()
Else!If 1=2
Line 1,249 ⟶ 1,446:
Else
NOPE()
End</langsyntaxhighlight>
 
=={{header|Babel}}==
Line 1,255 ⟶ 1,452:
===Simple select===
 
<langsyntaxhighlight lang="babel">
"foo" "bar" 3 4 > sel <<
</syntaxhighlight>
</lang>
 
Prints "foo" since '3 4 >' evaluates to false, which causes sel to remove "bar" from the stack.
Line 1,263 ⟶ 1,460:
===If-Then-Else===
 
<langsyntaxhighlight lang="babel">
{3 4 >}
{"foo"}
Line 1,269 ⟶ 1,466:
ifte
<<
</syntaxhighlight>
</lang>
 
Prints "bar" because the first line is the "if", the second line is the "then" and the last line is the "else", and '3 4 >' evaluates to false.
Line 1,275 ⟶ 1,472:
===Conditional===
 
<langsyntaxhighlight lang="babel">
({3 4 >} {"Three is greater than four" }
{3 3 >} {"Three is greater than three"}
Line 1,282 ⟶ 1,479:
cond
<<
</syntaxhighlight>
</lang>
 
Prints "Three is greater than two", as expected.
Line 1,292 ⟶ 1,489:
BASIC can use the if statement to perform conditional operations:
 
<langsyntaxhighlight lang="basic">10 LET A%=1: REM A HAS A VALUE OF TRUE
20 IF A% THEN PRINT "A IS TRUE"
30 WE CAN OF COURSE USE EXPRESSIONS
Line 1,298 ⟶ 1,495:
50 IF NOT(A%) THEN PRINT "A IS FALSE"
60 REM SOME VERSIONS OF BASIC PROVIDE AN ELSE KEYWORD
70 IF A% THEN PRINT "A IS TRUE" ELSE PRINT "A IS FALSE"</langsyntaxhighlight>
 
Here are code snippets from a more modern variant that does not need line numbers:
Line 1,306 ⟶ 1,503:
Single line IF does not require END IF
 
<langsyntaxhighlight lang="qbasic">IF x = 0 THEN doSomething
IF x < 0 THEN doSomething ELSE doOtherThing</langsyntaxhighlight>
 
Multi-line IF:
 
<langsyntaxhighlight lang="qbasic">IF x > 0 AND x < 10 THEN
'do stuff
ELSE IF x = 0 THEN
Line 1,317 ⟶ 1,514:
ELSE
'do more stuff
END IF</langsyntaxhighlight>
 
Like in [[#C|C]], any non-zero value is interpreted as True:
 
<langsyntaxhighlight lang="qbasic">IF aNumber THEN
'the number is not 0
ELSE
'the number is 0
END IF</langsyntaxhighlight>
 
===select case===
Line 1,332 ⟶ 1,529:
The condition in each case branch can be one or more constants or variables, a range or an expression.
 
<langsyntaxhighlight lang="qbasic">SELECT CASE expression
CASE 1
'do stuff
Line 1,343 ⟶ 1,540:
CASE ELSE
'default case
END SELECT</langsyntaxhighlight>
 
===Computed ON-GOTO===
Line 1,351 ⟶ 1,548:
or:
 
<langsyntaxhighlight lang="basic">10 INPUT "Enter 1,2 or 3: ";v
20 GOTO v * 100
99 STOP
Line 1,359 ⟶ 1,556:
210 STOP
300 PRINT "Cherry"
310 STOP</langsyntaxhighlight>
 
===Conditional loops===
Line 1,365 ⟶ 1,562:
Some variants of basic support conditional loops:
 
<langsyntaxhighlight lang="bbcbasic">10 REM while loop
20 L=0
30 WHILE L<5
Line 1,376 ⟶ 1,573:
100 PRINT L
110 L=L+1
120 UNTIL L>5</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
Applesoft BASIC does not have ELSE, only the IF-THEN structure and computed ON-GOSUB and ON-GOTO
<syntaxhighlight lang="applesoftbasic"> 10 LET X = 1
20 IF X THEN PRINT "X IS TRUE"
30 IF NOT X THEN PRINT "X IS FALSE"
40 ON X GOSUB 100,200,300
50 ON X GOTO 300,200,100
100 PRINT "APPLE": RETURN
200 PRINT "BANANA": RETURN
300 PRINT "CHERRY"</syntaxhighlight>
 
=={{header|BASIC256}}==
Line 1,418 ⟶ 1,626:
</pre>
I think this test shows that nested if statements parse as they do in c.
<syntaxhighlight lang="basic256">
<lang BASIC256>
for i = 0 to 1
for j = 0 to 1
Line 1,438 ⟶ 1,646:
next j
next i
</syntaxhighlight>
</lang>
 
=={{header|Batch File}}==
IF syntax:
<langsyntaxhighlight lang="dos">
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
Line 1,457 ⟶ 1,665:
GEQ - greater than or equal
/I case insensitive string compares
</syntaxhighlight>
</lang>
The ELSE clause must be on the same line as the command after the IF.
For example:
<langsyntaxhighlight lang="dos">
IF EXIST %filename% (
del %filename%
Line 1,466 ⟶ 1,674:
echo %filename% not found
)
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> REM Single-line IF ... THEN ... ELSE (ELSE clause is optional):
IF condition% THEN statements ELSE statements
 
Line 1,494 ⟶ 1,702:
 
REM ON ... PROC (ELSE clause is optional):
ON expression% PROCone, PROCtwo ... ELSE statements</langsyntaxhighlight>
 
=={{header|beeswax}}==
Line 1,501 ⟶ 1,709:
 
The 4 conditional operators are:
<syntaxhighlight lang="beeswax">
<lang Beeswax>
' lstack top value == 0 ? skip next instruction : don’t skip next instruction.
" lstack top value > 0 ? skip next instruction : don’t skip next instruction.
K lstack top value == 2nd value ? skip next instruction : don’t skip next instruction.
L lstack top value > 2nd value ? skip next instruction : don’t skip next instruction.</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight Beeswaxlang="beeswax">_`Enter integer n:`T'p`n = 0`>N`Enter integer m:`T'p`m = 0`>` and `Kp`m = n`;
>`n > 0`d >`m > 0`d >Lp`m > n`;
>`m < n`;</langsyntaxhighlight>
 
Example output:
<langsyntaxhighlight Beeswaxlang="beeswax">Enter integer n:
i3
n > 0
Enter integer m:
i0
m = 0 and m < n</langsyntaxhighlight>
 
=={{header|Befunge}}==
Line 1,525 ⟶ 1,733:
These snippets input a number and use the conditional operators to print a "0" if it is zero and an "X" otherwise.
 
<langsyntaxhighlight lang="befunge">v > "X",@ non-zero
> & |
> "0",@ zero</langsyntaxhighlight>
 
'''#''' is the skip command.
It unconditionally skips one character, allowing a little flexibility in flow control.
 
<langsyntaxhighlight lang="befunge">& #v_ "0",@ zero
> "X",@ non-zero</langsyntaxhighlight>
 
=={{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}}==
===if-else===
<langsyntaxhighlight lang="blz">
if i % 2 == 0
print("even")
Line 1,543 ⟶ 1,755:
print("odd")
end
</syntaxhighlight>
</lang>
 
=={{header|Bori}}==
===if-elif-else===
<langsyntaxhighlight lang="bori">
if (i == 0)
return "zero";
Line 1,554 ⟶ 1,766:
else
return "even";
</syntaxhighlight>
</lang>
 
=={{header|BQN}}==
The basic method of control flow in BQN is implemented using first-class functions and Choose (<code>◶</code>). Using Choose, we can implement some basic control structures:
<langsyntaxhighlight lang="bqn">If ← {𝕏⍟𝕎@}´ # Also Repeat
IfElse ← {c‿T‿F: c◶F‿T@}
While ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´ # While 1‿{... to run forever
Line 1,568 ⟶ 1,780:
Select ← {(⊑𝕩)◶(1↓𝕩)@}
Switch ← {c←⊑𝕩 ⋄ m‿a←<˘⍉∘‿2⥊1↓𝕩 ⋄ (⊑a⊐C)◶m@}
Test ← {fn←{C‿A𝕊e:C◶A‿E}´𝕩⋄Fn@}</langsyntaxhighlight>
 
The other method of branching is using function predicates, which can be used in any blocks for an if-else like conditional:
<langsyntaxhighlight lang="bqn">{
a<b ? a+↩1 ; # If
a<c ? c-↩1 ; # Else If
a-↩2 # Else
}</langsyntaxhighlight>
 
However, they act like any other block header, so the variables defined in each predicate segment do not exist in their else and else if condition. Block Headers in general provide a rudimentary form of control flow (checking for exact matches and wildcards), but these are much more constrained than a general conditional.
Line 1,591 ⟶ 1,803:
The following expression writes "That's what I thought." to your screen and evaluates to the expression "Right".
 
<langsyntaxhighlight lang="bracmat"> 2+2:5
& put$"Strange, must check that Bracmat interpreter."
& 0
| put$"That's what I thought."
& Right</langsyntaxhighlight>
 
=== switch-like branching ===
Line 1,601 ⟶ 1,813:
In the following example, the resulting expression is a single node containing "4".
 
<langsyntaxhighlight lang="bracmat"> 2+2
: ( (<3|>5)
& put$"Not quite, must check that Bracmat interpreter."
Line 1,609 ⟶ 1,821:
& put$"That's what I thought."
)
</langsyntaxhighlight>
 
=={{header|Brainf***}}==
Line 1,616 ⟶ 1,828:
Thus in the following sequence:
 
<syntaxhighlight lang ="bf">[.]</langsyntaxhighlight>
 
The . instruction will be skipped, while the following sequence
 
<syntaxhighlight lang ="bf">+[.]</langsyntaxhighlight>
 
will result in an infinite loop. Finally, in the following sequence
 
<syntaxhighlight lang ="bf">+[.-]</langsyntaxhighlight>
 
The . instruction will be executed once.
Line 1,632 ⟶ 1,844:
Using the ''Choose'' command:
 
<langsyntaxhighlight lang="burlesque">
blsq ) 9 2.%{"Odd""Even"}ch
"Odd"
</syntaxhighlight>
</lang>
 
Using the ''If'' command (produce next even number if odd):
 
<langsyntaxhighlight lang="burlesque">
blsq ) 9^^2.%{+.}if
10
blsq ) 10^^2.%{+.}if
10
</syntaxhighlight>
</lang>
 
Using the ''IfThenElse'' command (produce next odd number if even or previous even number if odd):
 
<langsyntaxhighlight lang="burlesque">
blsq ) 10^^2.%{-.}\/{+.}\/ie
11
blsq ) 9^^2.%{-.}\/{+.}\/ie
8
</syntaxhighlight>
</lang>
 
Emulating Switch-Case behaviour:
 
<langsyntaxhighlight lang="burlesque">
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Banana"Fi!!
"Like Bananas"
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Apple"Fi!!
"Hate Apples"
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Line 1,671 ⟶ 1,883:
===if-elseif-else===
 
<langsyntaxhighlight lang="csharp">if (condition)
{
// Some Task
Line 1,687 ⟶ 1,899:
{
// Some Task
}</langsyntaxhighlight>
 
===Ternary===
 
<langsyntaxhighlight lang="csharp">// if condition is true var will be set to 1, else 2.
int var = condition ? 1 : 2;</langsyntaxhighlight>
 
===switch===
 
<langsyntaxhighlight lang="csharp">switch (value)
{
case 1:
Line 1,708 ⟶ 1,920:
// Some task
break;
}</langsyntaxhighlight>
 
If fall through algorithms are required use the goto keyword.
 
<langsyntaxhighlight lang="csharp">switch (value)
{
case 1:
Line 1,726 ⟶ 1,938:
// Some task
break;
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 1,741 ⟶ 1,953:
Selecting a type depending on a compile time condition
 
<langsyntaxhighlight lang="cpp">template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;
 
template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
Line 1,757 ⟶ 1,969:
long int, // in that case, we'll need a long int
int> // otherwise an int will do
::type myvar; // define variable myvar with that type</langsyntaxhighlight>
 
=={{header|Clean}}==
Line 1,763 ⟶ 1,975:
There are no ''then'' or ''else'' keyword in Clean.
The second argument of <tt>if</tt> is the then-part, the third argument is the else-part.
<langsyntaxhighlight lang="clean">bool2int b = if b 1 0</langsyntaxhighlight>
 
===case-of===
<langsyntaxhighlight lang="clean">case 6 * 7 of
42 -> "Correct"
_ -> "Wrong" // default, matches anything</langsyntaxhighlight>
 
===function alternatives===
<langsyntaxhighlight lang="clean">answer 42 = True
answer _ = False</langsyntaxhighlight>
 
===guards===
<langsyntaxhighlight lang="clean">answer x
| x == 42 = True
| otherwise = False
Line 1,782 ⟶ 1,994:
n | n < 0 -> "Not even close"
42 -> "Correct"
// no default, could result in a run-time error</langsyntaxhighlight>
 
=={{header|Clipper}}==
'''if-elseif-else-endif'''
<langsyntaxhighlight lang="clipper">IF x == 1
SomeFunc1()
ELSEIF x == 2
Line 1,792 ⟶ 2,004:
ELSE
SomeFunc()
ENDIF</langsyntaxhighlight>
 
'''do case'''
<langsyntaxhighlight lang="clipper">DO CASE
CASE x == 1
SomeFunc1()
Line 1,802 ⟶ 2,014:
OTHERWISE
SomeFunc()
ENDCASE</langsyntaxhighlight>
 
=={{header|Clojure}}==
===if-then-else===
<langsyntaxhighlight lang="clojure">(if (= 1 1) :yes :no) ; returns :yes
 
(if (= 1 2) :yes :no) ; returns :no
 
(if (= 1 2) :yes) ; returns nil</langsyntaxhighlight>
 
===when===
Similar to if, but body in an implicit do block allowing multiple statements.
No facility for providing an else. <code>when</code> is defined as a macro.
<langsyntaxhighlight lang="clojure">(when x
(print "hello")
(println " world")
5) ; when x is logical true, prints "hello world" and returns 5; otherwise does nothing, returns nil</langsyntaxhighlight>
 
===cond===
The cond macro takes a series of test/result pairs, evaluating each test until one resolves to logical true, then evaluates its result.
Returns nil if none of the tests yield true.
<langsyntaxhighlight lang="clojure">(cond
(= 1 2) :no) ; returns nil
 
(cond
(= 1 2) :no
(= 1 1) :yes) ; returns :yes</langsyntaxhighlight>
Since non-nil objects are logical true, by convention the keyword :else is used to yield a default result.
<langsyntaxhighlight lang="clojure">(cond
(= 1 2) :no
:else :yes) ; returns :yes</langsyntaxhighlight>
 
===condp===
Similar to cond, but useful when each test differs by only one variant.
<langsyntaxhighlight lang="clojure">(condp < 3
4 :a ; cond equivalent would be (< 4 3) :a
3 :b
2 :c
1 :d) ; returns :c</langsyntaxhighlight>
Optionally takes a final arg to be used as the default result if none of the tests match.
<langsyntaxhighlight lang="clojure">(condp < 3
4 :a
3 :b
:no-match) ; returns :no-match</langsyntaxhighlight>
 
===case===
{{Works with|Clojure|1.2}}
<langsyntaxhighlight lang="clojure">(case 2
0 (println "0")
1 (println "1")
2 (println "2")) ; prints 2.</langsyntaxhighlight>
 
=={{header|CMake}}==
<langsyntaxhighlight lang="cmake">set(num 5)
 
if(num GREATER 100)
Line 1,864 ⟶ 2,076:
message("${num} is small.")
message("We might want a bigger number.")
endif()</langsyntaxhighlight>
 
The if() and elseif() commands evaluate boolean expressions like ''num GREATER 100''; refer to [http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:if cmake --help-command if].
Line 1,871 ⟶ 2,083:
=={{header|COBOL}}==
===if-then-else===
<langsyntaxhighlight lang="cobol">if condition-1
imperative-statement-1
else
Line 1,889 ⟶ 2,101:
imperative-statement-2
end-if
end-if</langsyntaxhighlight>
 
===evaluate===
<langsyntaxhighlight lang="cobol">evaluate identifier-1
when 'good'
good-imperative-statement
Line 1,924 ⟶ 2,136:
when other
default-imperative-statement
end-evaluate</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
Line 1,930 ⟶ 2,142:
===if-then-else===
 
<langsyntaxhighlight lang="coffeescript">
if n == 1
console.log "one"
Line 1,937 ⟶ 2,149:
else
console.log "other"
</syntaxhighlight>
</lang>
 
===switch===
 
<langsyntaxhighlight lang="coffeescript">n = 1
 
switch n
Line 1,950 ⟶ 2,162:
else
console.log "other"
</syntaxhighlight>
</lang>
 
===ternary expressions===
Line 1,956 ⟶ 2,168:
CoffeeScript is very expression-oriented, so you can assign the "result" of an if-then to a variable.
 
<langsyntaxhighlight lang="coffeescript">s = if condition then "yup" else "nope"
 
# alternate form
Line 1,962 ⟶ 2,174:
if condition
then "yup"
else "nope"</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
===if-elseif-else===
'''Compiler:''' [[ColdFusion]] any version
<langsyntaxhighlight lang="cfm"><cfif x eq 3>
do something
<cfelseif x eq 4>
Line 1,973 ⟶ 2,185:
<cfelse>
do something else
</cfif></langsyntaxhighlight>
 
===switch===
'''Compiler:''' [[ColdFusion]] any version
<langsyntaxhighlight lang="cfm"><cfswitch expression="#x#">
<cfcase value="1">
do something
Line 1,987 ⟶ 2,199:
do something
</cfdefaultcase>
</cfswitch></langsyntaxhighlight>
 
=={{header|Comal}}==
===IF/THEN===
<langsyntaxhighlight Comallang="comal">IF condition THEN PRINT "True"</langsyntaxhighlight>
 
===IF/THEN/ELSE===
<langsyntaxhighlight Comallang="comal">IF condition THEN
PRINT "True"
ELSE
PRINT "False"
ENDIF</langsyntaxhighlight>
 
===IF/THEN/ELIF/ELSE===
<langsyntaxhighlight Comallang="comal">IF choice=1 THEN
PRINT "One"
ELIF choice=2 THEN
PRINT "Two"
ELSE
Print "None of the above"</langsyntaxhighlight>
 
===CASE/WHEN===
<syntaxhighlight lang="comal">
<lang Comal>
CASE choice OF
WHEN 1
Line 2,018 ⟶ 2,230:
PRINT "Some other choice"
ENDCASE
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 2,029 ⟶ 2,241:
Should the result be non-nil, it goes on to evaluate and returnm the results of the 'then' part, otherwise, when present, it evaluates and returns the result of the 'else' part. Should there be no 'else' part, it returns nil.
 
<langsyntaxhighlight lang="lisp">(if (= val 42)
"That is the answer to life, the universe and everything"
"Try again") ; the else clause here is optional</langsyntaxhighlight>
 
==== <code>when</code> and <code>unless</code> ====
Line 2,042 ⟶ 2,254:
The (cond ...) construct acts as both an if..elseif...elseif...else operator and a switch, returning the result of the form associated with the first non-nil predicate.
 
<langsyntaxhighlight lang="lisp">(cond ((= val 1) (print "no"))
((and (> val 3) (< val 6)) (print "yes"))
((> val 99) (print "too far"))
(T (print "no way, man!")))</langsyntaxhighlight>
 
=={{header|Computer/zero Assembly}}==
Line 2,054 ⟶ 2,266:
===if-elseif-else===
 
<langsyntaxhighlight lang="crack">if (condition)
{
// Some Task
Line 2,070 ⟶ 2,282:
{
// Some Task
}</langsyntaxhighlight>
 
===Ternary===
 
<langsyntaxhighlight lang="crack">
// if condition is true var will be set to 1, else false.
int var = condition ? 1 : 2;
</syntaxhighlight>
</lang>
=={{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>
 
=={{header|D}}==
:''See [[Conditional Structures#C|C]], sans the preprocessor.''
 
<langsyntaxhighlight lang="d">void main() {
enum int i = 5;
 
Line 2,130 ⟶ 2,355:
// default: // Forbidden in final switches.
}
}</langsyntaxhighlight>
 
=={{header|Dao}}==
===If Elif Else===
<langsyntaxhighlight lang="java">a = 3
if( a == 1 ){
io.writeln( 'a == 1' )
Line 2,141 ⟶ 2,366:
}else{
io.writeln( 'a is neither 1 nor 3' )
}</langsyntaxhighlight>
 
===Switch Case===
<langsyntaxhighlight lang="java">a = 3
switch( a ){
case 0: io.writeln( 'case 0' )
Line 2,150 ⟶ 2,375:
case 3, 4, 5: io.writeln( 'case 3,4,5' )
default: io.writeln( 'default' )
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 2,158 ⟶ 2,383:
=={{header|Deluge}}==
 
<langsyntaxhighlight lang="deluge">if (input.Field == "Hello World") {
sVar = "good";
} else if (input.Field == "Bye World") {
Line 2,164 ⟶ 2,389:
} else {
sVar = "neutral";
}</langsyntaxhighlight>
 
=={{header|DM}}==
===if-elseif-else===
<langsyntaxhighlight DMlang="dm">if (condition)
// Do thing, DM uses indentation for control flow.
 
Line 2,179 ⟶ 2,404:
else
// Do thing
</syntaxhighlight>
</lang>
 
===Ternary===
<langsyntaxhighlight DMlang="dm">// x will be 1 if condition is a true value, 2 otherwise.
var/x = condition ? 1 : 2
</syntaxhighlight>
</lang>
 
===Switch===
<langsyntaxhighlight DMlang="dm">switch (value)
if (0)
// Do thing if zero
Line 2,201 ⟶ 2,426:
else
// Fallback if nothing was matched.
</syntaxhighlight>
</lang>
 
=={{header|Dragon}}==
===if-then-else===
<langsyntaxhighlight lang="dragon">if(a == b)
{
add()
Line 2,214 ⟶ 2,439:
{
both()
}</langsyntaxhighlight>
 
=={{header|DWScript}}==
Line 2,221 ⟶ 2,446:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">if a:
pass
elseif b:
pass
else: # c, maybe?
pass</langsyntaxhighlight>
 
=={{header|E}}==
Line 2,232 ⟶ 2,457:
===if-then-else===
 
<langsyntaxhighlight lang="e">if (okay) {
println("okay")
} else if (!okay) {
Line 2,238 ⟶ 2,463:
} else {
println("not my day")
}</langsyntaxhighlight>
 
The pick/2 message of booleans provides a value-based conditional:
 
<langsyntaxhighlight lang="e">println(okay.pick("okay", "not okay"))</langsyntaxhighlight>
 
It can therefore be used to construct a Smalltalk-style conditional:
 
<langsyntaxhighlight lang="e">okay.pick(fn {
println("okay")
}, fn {
println("not okay")
})()</langsyntaxhighlight>
 
All of the above conditionals are expressions and have a usable return value.
Line 2,258 ⟶ 2,483:
E's "switch" allows pattern matching.
 
<langsyntaxhighlight lang="e">def expression := ["+", [1, 2]]
 
def value := switch (expression) {
Line 2,264 ⟶ 2,489:
match [`*`, [a, b]] { a * b }
match [op, _] { throw(`unknown operator: $op`) }
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
<lang>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"
.
.</lang>
</syntaxhighlight>
 
=={{header|Efene}}==
Line 2,281 ⟶ 2,508:
Since if and case do pattern matching, if an if or case expression don't match some of the patterns, the program will crash
 
<langsyntaxhighlight lang="efene">
show_if_with_parenthesis = fn (Num) {
if (Num == 1) {
Line 2,341 ⟶ 2,568:
show_switch_with_parenthesis(random.uniform(3))
show_switch_without_parenthesis(random.uniform(3))
}</langsyntaxhighlight>
 
=={{header|Ela}}==
Line 2,347 ⟶ 2,574:
===if-then-else===
 
<langsyntaxhighlight lang="ela">if x < 0 then 0 else x</langsyntaxhighlight>
 
===Guards===
 
<langsyntaxhighlight lang="ela">getX x | x < 0 = 0
| else = x</langsyntaxhighlight>
 
===Pattern matching===
 
<langsyntaxhighlight lang="ela">force (x::xs) = x :: force xs
force [] = []</langsyntaxhighlight>
 
===match expression===
 
<langsyntaxhighlight lang="ela">force lst = match lst with
x::xs = x :: force xs
[] = []</langsyntaxhighlight>
 
 
=={{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,378 ⟶ 2,636:
case expressions take an expression and match it to a pattern with optional guards.
 
<langsyntaxhighlight lang="erlang">case X of
{N,M} when N > M -> M;
{N,M} when N < M -> N;
_ -> equal
end.</langsyntaxhighlight>
 
===if===
Line 2,389 ⟶ 2,647:
Guards must evaluate to true or false so true is the catch-all clause.
 
<langsyntaxhighlight lang="erlang">{N,M} = X,
if
N > M -> M;
N < M -> N;
true -> equal
end.</langsyntaxhighlight>
 
===Function Clauses===
Line 2,400 ⟶ 2,658:
Functions can have multiple clauses tested in order.
 
<langsyntaxhighlight lang="erlang">test({N,M}) when N > M -> M;
test({N,M}) when N < M -> N;
test(_) -> equal.</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
printfn "%s" (if 3<2 then "3 is less than 2" else "3 is not less than 2")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,420 ⟶ 2,678:
===?===
? is for when you don't need branching, but only need to select between two different values.
<langsyntaxhighlight lang="factor">
t 1 2 ? ! returns 1
</syntaxhighlight>
</lang>
 
===if===
<langsyntaxhighlight lang="factor">t [ 1 ] [ 2 ] if ! returns 1</langsyntaxhighlight>
 
===cond===
<langsyntaxhighlight lang="factor">{ { [ t ] [ 1 ] } { [ f ] [ 2 ] } } cond ! returns 1</langsyntaxhighlight>
 
===case===
<langsyntaxhighlight lang="factor">t { { t [ 1 ] } { f [ 2 ] } } case ! returns 1</langsyntaxhighlight>
 
===when===
<langsyntaxhighlight lang="factor">t [ "1" print ] when ! prints 1</langsyntaxhighlight>
 
===unless===
<langsyntaxhighlight lang="factor">f [ "1" print ] unless ! prints 1</langsyntaxhighlight>
 
=={{header|FALSE}}==
<syntaxhighlight lang ="false">condition[body]?</langsyntaxhighlight>
Because there is no "else", you need to stash the condition if you want the same effect:
<langsyntaxhighlight lang="false">$[\true\]?~[false]?</langsyntaxhighlight>
or
<langsyntaxhighlight lang="false">$[%true0~]?~[false]?</langsyntaxhighlight>
 
=={{header|Fancy}}==
Line 2,450 ⟶ 2,708:
 
===if:then:===
<langsyntaxhighlight lang="fancy">if: (x < y) then: {
"x < y!" println # will only execute this block if x < y
}
</syntaxhighlight>
</lang>
 
===if:then:else::===
<langsyntaxhighlight lang="fancy">if: (x < y) then: {
"x < y!" println # will only execute this block if x < y
} else: {
"x not < y!" println
}
</syntaxhighlight>
</lang>
 
 
===if_true:===
<langsyntaxhighlight lang="fancy">x < y if_true: {
"x < y!" println # will only execute this block if x < y
}
</syntaxhighlight>
</lang>
 
===if_false: / if_nil:===
<langsyntaxhighlight lang="fancy">x < y if_false: {
"x not < y!" println # will only execute this block if x >= y
}
</syntaxhighlight>
</lang>
 
===if_true:else:===
<langsyntaxhighlight lang="fancy">x < y if_true: {
"x < y!" println
} else: {
"x >= y!" println
}
</syntaxhighlight>
</lang>
 
===if_false:else:===
<langsyntaxhighlight lang="fancy">x < y if_false: {
"x >= y!"
} else: {
"x < y!" println
}
</syntaxhighlight>
</lang>
 
===if:===
<langsyntaxhighlight lang="fancy">{ "x < y!" println } if: (x < y) # analog, but postfix</langsyntaxhighlight>
 
 
===unless:===
<langsyntaxhighlight lang="fancy">{ "x not < y!" } unless: (x < y) # same here</langsyntaxhighlight>
 
=={{header|Forth}}==
===IF-ELSE===
<langsyntaxhighlight lang="forth">( condition ) IF ( true statements ) THEN
( condition ) IF ( true statements ) ELSE ( false statements ) THEN</langsyntaxhighlight>
example:
<langsyntaxhighlight lang="forth">10 < IF ." Less than 10" ELSE ." Greater than or equal to 10" THEN</langsyntaxhighlight>
 
===CASE-OF===
<langsyntaxhighlight lang="forth">( n -- ) CASE
( integer ) OF ( statements ) ENDOF
( integer ) OF ( statements ) ENDOF
( default instructions )
ENDCASE</langsyntaxhighlight>
example: a simple CASE selection
<langsyntaxhighlight lang="forth">: test-case ( n -- )
CASE
0 OF ." Zero!" ENDOF
1 OF ." One!" ENDOF
." Some other number!"
ENDCASE ;</langsyntaxhighlight>
 
===Execution vector===
To obtain the efficiency of a C switch statement for enumerations, one needs to construct one's own execution vector.
<langsyntaxhighlight lang="forth">: switch
CREATE ( default-xt [count-xts] count -- ) DUP , 0 DO , LOOP ,
DOES> ( u -- ) TUCK @ MIN 1+ CELLS + @ EXECUTE ;
Line 2,540 ⟶ 2,798:
 
8 digit \ eight
34 digit \ Out of range!</langsyntaxhighlight>
===Execution Vector 2===
This method was used by the late Jim Kalihan and Dr. Julian Nobel
<langsyntaxhighlight Forthlang="forth">: CASE: ( <name>) CREATE ;
 
\ lookup execution token and compile
Line 2,558 ⟶ 2,816:
 
\ Usage: 3 SELECT
</syntaxhighlight>
</LANG>
 
=={{header|Fortran}}==
Line 2,564 ⟶ 2,822:
===IF-THEN-ELSE===
ANSI FORTRAN 77 or later has an IF-THEN-ELSE structure:
<langsyntaxhighlight lang="fortran">if ( a .gt. 20.0 ) then
q = q + a**2
else if ( a .ge. 0.0 ) then
Line 2,570 ⟶ 2,828:
else
q = q - a
end if</langsyntaxhighlight>
 
===SELECT-CASE===
ISO Fortran 90 or later has a SELECT-CASE structure:
<langsyntaxhighlight lang="fortran">select case (i)
case (21:) ! matches all integers greater than 20
q = q + i**2
Line 2,581 ⟶ 2,839:
case default ! matches all other integers (negative in this particular case)
q = q - I
end select</langsyntaxhighlight>
 
===WHERE-ELSEWHERE===
ISO Fortran 90 and later has a concurrent, array-expression-based WHERE-ELSEWHERE structure. The logical expressions in WHERE and ELSEWHERE clauses must be array-values. All statements inside the structure blocks must be array-valued. Furthermore, all array-valued expressions and statements must have the same "shape". That is, they must have the same number of dimensions, and each expression/statement must have the same sizes in corresponding dimensions as each other expression/statement. For each block, wherever the logical expression is true, the corresponding elements of the array expressions/statements are evaluated/executed.
<langsyntaxhighlight lang="fortran">! diffusion grid time step
where (edge_type(1:n,1:m) == center)
anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5
Line 2,615 ⟶ 2,873:
elsewhere ! sink/source, does not change
anew(1:n,1:m) = a(1:n,1:m)
end where</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
===IF-ELSEIF-ELSE-END IF===
<langsyntaxhighlight lang="freebasic">Dim a As Integer = 1
If a = 1 Then
sub1
Line 2,626 ⟶ 2,884:
Else
sub3
End If</langsyntaxhighlight>
 
===SELECT-CASE===
<langsyntaxhighlight lang="freebasic">Dim a As Integer = 1
Select Case a
Case 1
Line 2,637 ⟶ 2,895:
Case Else
sub3
End Select</langsyntaxhighlight>
 
===IFF===
<langsyntaxhighlight lang="freebasic">Dim b As Boolean = True
Dim i As Integer = IIf(b, 1, 2)</langsyntaxhighlight>
 
===ON-GOTO===
<langsyntaxhighlight lang="freebasic">Dim a As Integer = 1
On a Goto label1, label2</langsyntaxhighlight>
 
===IF-GOTO (deprecated)===
<langsyntaxhighlight lang="freebasic">Dim b As Boolean = True
If b Goto label</langsyntaxhighlight>
 
===ON-GOSUB (legacy dialects only)===
<langsyntaxhighlight lang="freebasic">Dim a As Integer = 1
On a Gosub label1, label2</langsyntaxhighlight>
 
===#IF-#ELSEIF-#ELSE-#ENDIF (preprocessor)===
<langsyntaxhighlight lang="freebasic">#DEFINE WORDSIZE 16
#IF (WORDSIZE = 16)
' Do some some 16 bit stuff
Line 2,663 ⟶ 2,921:
#ELSE
#ERROR WORDSIZE must be set to 16 or 32
#ENDIF</langsyntaxhighlight>
 
===#IFDEF (preprocessor)===
<langsyntaxhighlight lang="freebasic">#DEFINE _DEBUG
#IFDEF _DEBUG
' Special statements for debugging
#ENDIF</langsyntaxhighlight>
 
===#IFNDEF (preprocessor)===
<langsyntaxhighlight lang="freebasic">#IFNDEF _DEBUG
#DEFINE _DEBUG
#ENDIF</langsyntaxhighlight>
 
=={{header|friendly interactive shell}}==
===if-then-else===
<langsyntaxhighlight lang="fishshell">set var 'Hello World'
if test $var = 'Hello World'
echo 'Welcome.'
Line 2,685 ⟶ 2,943:
else
echo 'Huh?'
end</langsyntaxhighlight>
 
===switch===
case statements take wildcards as arguments, but because of syntax quirk, they have to be quoted (just like in Powershell), otherwise they would match files in current directory. Unlike switch statements in C, they don't fall through. To match something that would be matched if nothing was matches use wildcard that matches everything, the language doesn't have default statement.
<langsyntaxhighlight lang="fishshell">switch actually
case az
echo The word is "az".
Line 2,700 ⟶ 2,958:
case '*'
echo Neither begins with a or ends with z.
end</langsyntaxhighlight>
 
=={{header|Futhark}}==
Line 2,707 ⟶ 2,965:
Futhark supports branching with a syntax common to most functional languages.
 
<langsyntaxhighlight lang="futhark">
if <condition> then <truebranch> else <falsebranch>
</syntaxhighlight>
</lang>
 
 
=={{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>
 
=={{header|GAP}}==
=== if-then-else ===
<langsyntaxhighlight lang="gap">if <condition> then
<statements>
elif <condition> then
Line 2,719 ⟶ 3,021:
else
<statements>
fi;</langsyntaxhighlight>
 
 
=={{header|Go}}==
Line 2,725 ⟶ 3,028:
===If===
Simplest usage is,
<langsyntaxhighlight lang="go">if booleanExpression {
statements
}</langsyntaxhighlight>
The braces are required, even around a single statement.
<langsyntaxhighlight lang="go">if booleanExpression {
statements
} else {
other
statements
}</langsyntaxhighlight>
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,
<langsyntaxhighlight lang="go">if booleanExpression1 {
statements
} else if booleanExpression2 {
otherStatements
}
</syntaxhighlight>
</lang>
If allows a statement to be included ahead of the condition. This is commonly a short variable declaration, as in,
<langsyntaxhighlight lang="go">if x := fetchSomething(); x > 0 {
DoPos(x)
} else {
DoNeg(x)
}</langsyntaxhighlight>
In this case the scope of x is limited to if statement.
 
===Switch===
Simple usage is,
<langsyntaxhighlight lang="go">switch {
case booleanExpression1:
statements
Line 2,762 ⟶ 3,065:
resort
statements
}</langsyntaxhighlight>
Because switch can work with any number of arbitrary boolean expressions, it replaces if/elseif chains often found in other programming languages.
 
Switch can also switch on the value of an expression, as in,
<langsyntaxhighlight lang="go">switch expressionOfAnyType {
case value1:
statements
Line 2,772 ⟶ 3,075:
other
statements
}</langsyntaxhighlight>
As shown, multiple values can be listed for a single case clause.
Since go is statically typed, the types of value1, 2, 3, and 4 must match the type of the expression.
 
As with if, a local statement such as a short variable declaration can precede the expression. If there is no expression, the statement is still marked by a semicolon:
<langsyntaxhighlight lang="go">switch x := fetch(); {
case x == "cheese":
statements
Line 2,783 ⟶ 3,086:
other
statements
}</langsyntaxhighlight>
Also, as with if, the scope of x is limited to the switch statement.
 
Line 2,789 ⟶ 3,092:
 
An interesting example:
<langsyntaxhighlight lang="go">switch {
case booleanExpression1:
default:
Line 2,798 ⟶ 3,101:
other
statements
}</langsyntaxhighlight>
Case expressions are evaluated in order, then if none are true, the default clause is executed.
 
Another statement that interacts with switch is break. It breaks from the switch statement and so will not break from a surrounding for statement. The following example prints "I want out!" endlessly.
<langsyntaxhighlight lang="go">for {
switch {
case true:
Line 2,808 ⟶ 3,111:
}
fmt.Println("I want out!")
}</langsyntaxhighlight>
Labels provide the desired capability. The following prints "I'm off!"
<langsyntaxhighlight lang="go">treadmill: for {
switch {
case true:
Line 2,816 ⟶ 3,119:
}
}
fmt.Println("I'm off!")</langsyntaxhighlight>
 
=={{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}}==
'''if-elseif-else-endif'''
<langsyntaxhighlight lang="visualfoxpro">IF x == 1
SomeFunc1()
ELSEIF x == 2
Line 2,826 ⟶ 3,194:
ELSE
SomeFunc()
ENDIF</langsyntaxhighlight>
 
'''do case'''
<langsyntaxhighlight lang="visualfoxpro">DO CASE
CASE x == 1
SomeFunc1()
Line 2,836 ⟶ 3,204:
OTHERWISE
SomeFunc()
ENDCASE</langsyntaxhighlight>
 
'''switch'''
While '''if-elseif-else-endif''' and '''do case''' constructions allows using of any expressions as conditions, the '''switch''' allows literals only in conditional '''case''' statements. The advantage of the '''switch''' command is that it is much faster.
<langsyntaxhighlight lang="visualfoxpro">SWITCH x
CASE 1
SomeFunc1()
Line 2,849 ⟶ 3,217:
OTHERWISE
SomeFunc()
ENDSWITCH</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
===if-then-else===
<langsyntaxhighlight lang="haskell">fac x = if x==0 then
1
else x * fac (x - 1)</langsyntaxhighlight>
 
===Guards===
<langsyntaxhighlight lang="haskell">fac x | x==0 = 1
| x>0 = x * fac (x-1)</langsyntaxhighlight>
===Pattern matching===
<langsyntaxhighlight lang="haskell">fac 0 = 1
fac x = x * fac (x-1)</langsyntaxhighlight>
===case statement===
<langsyntaxhighlight lang="haskell">fac x = case x of 0 -> 1
_ -> x * fac (x-1)</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">IF( a > 5 ) WRITE(Messagebox) a ! single line IF
 
IF( a >= b ) THEN
Line 2,879 ⟶ 3,247:
ELSE
WRITE(StatusBar) a, b, some_string
ENDIF</langsyntaxhighlight>
 
=={{header|HPPPL}}==
=== IF ===
Note that X has to be a number; else a runtime error occurs.
<langsyntaxhighlight HPPPLlang="hpppl">IF X THEN
// do if X is not 0
ELSE
// do if X is 0
END;</langsyntaxhighlight>
=== CASE ===
<langsyntaxhighlight HPPPLlang="hpppl">CASE
IF X == 1 THEN
// do stuff if X equals 1
Line 2,902 ⟶ 3,270:
DEFAULT
// do other stuff
END;</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">//'i' supports if, else, and else if
software {
a = 3
Line 2,916 ⟶ 3,284:
print("a = ", a)
end
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 2,922 ⟶ 3,290:
===if-then-else===
The control structure evaluates expr1 if expr0 succeeds and expr2 if it fails.
<langsyntaxhighlight Iconlang="icon">if expr0 then
expr1
else
expr2</langsyntaxhighlight>
===case-of===
The first successful selection expression will select and evaluate the specific case.
<langsyntaxhighlight Iconlang="icon">case expr0 of {
expr1 : expr2
expr3 : expr4
default: expr5
}</langsyntaxhighlight>
Note that expr1 and expr3 are expressions and not constants and it is possible to write expressions such as:
<langsyntaxhighlight Iconlang="icon">case x of {
f(x) | g(x) : expr2
s(x) & t(x) : expr4
default: expr5
}</langsyntaxhighlight>
===Compound expressions (blocks)===
In the examples below, multiple expressions can be grouped as in:
<syntaxhighlight lang="icon">{
<lang Icon>{
expr1
expr2
expr3
}</langsyntaxhighlight>
Which is equivalent to this:
<syntaxhighlight lang Icon="icon">{expr1; expr2; expr3}</langsyntaxhighlight>
For example the following, which will write 4, looks strange but is valid:
<langsyntaxhighlight Iconlang="icon">write({1;2;3;4})</langsyntaxhighlight>
The value of a compound expression is the value of the last expression in the block.
===Alternation===
Alternation of expressions yields a value for the first succeeding expression.
<langsyntaxhighlight Iconlang="icon"> expr1 | expr2 | expr3</langsyntaxhighlight>
===Conjunction===
Conjunctions yeild the value of the final expression provided all the previous expressions succeed.
<langsyntaxhighlight Iconlang="icon"> expr1 & expr2 & expr3</langsyntaxhighlight>
Alternately, conjunction can be written thus:
<langsyntaxhighlight Iconlang="icon"> (expr1, expr2, expr3)</langsyntaxhighlight>
===Conjunction, yielding a different result===
The alternate form of conjunction can be modified to produce a different result (other than the last)
<langsyntaxhighlight Iconlang="icon"> expr0(expr1, expr2, expr3)</langsyntaxhighlight>
For example:
<langsyntaxhighlight Iconlang="icon"> 2(expr1, expr2, expr3)</langsyntaxhighlight>
Yields the value of expr2 if all of the expressions succeed.
<br>A more complicated example showing non-constant expressions:
<langsyntaxhighlight Iconlang="icon"> f(expr1)(g(expr2)(expr3,expr4,expr5))</langsyntaxhighlight>
Note: if expr0 yields a value of type 'procedure' or 'string' the appropriate procedure (or operator) is invoked.
 
Line 2,975 ⟶ 3,343:
Basic if/then:
 
<langsyntaxhighlight lang="idl">if a eq 5 then print, "a equals five" [else print, "a is something else"]</langsyntaxhighlight>
 
Any one statement (like these print statements) can always be expanded into a {begin ... end} pair with any amount of code in between. Thus the above will expand like this:
 
<langsyntaxhighlight lang="idl">if a eq 5 then begin
... some code here ...
endif [else begin
... some other code here ...
endelse]</langsyntaxhighlight>
 
===case===
 
<langsyntaxhighlight lang="idl">case <expression> of
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[else: <command-else>]
endcase</langsyntaxhighlight>
 
(Or replace any of the commands with {begin..end} pairs)
Line 2,997 ⟶ 3,365:
===switch===
 
<langsyntaxhighlight lang="idl">switch <expression> of
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[else: <command-else>]
endswitch</langsyntaxhighlight>
 
The <tt>switch</tt> will execute all commands starting with the matching result, while the <tt>case</tt> will only execute the matching one.
Line 3,007 ⟶ 3,375:
===on_error===
 
<syntaxhighlight lang ="idl">on_error label</langsyntaxhighlight>
 
Will resume execution at label when an error is encountered. <tt>on_ioerror</tt> is similar but for IO errors.
Line 3,013 ⟶ 3,381:
=={{header|Inform 7}}==
===if-then-else===
<langsyntaxhighlight lang="inform7">[short form]
if N is 1, say "one.";
otherwise say "not one.";
Line 3,026 ⟶ 3,394:
 
[short and long forms can be negated with "unless"]
unless N is 1, say "not one."</langsyntaxhighlight>
 
===switch===
<langsyntaxhighlight lang="inform7">if N is:
-- 1: say "one.";
-- 2: say "two.";
-- otherwise: say "not one or two.";</langsyntaxhighlight>
 
===if-then-else in text===
<langsyntaxhighlight lang="inform7">say "[if N is 1]one[otherwise if N is 2]two[otherwise]three[end if].";
say "[unless N is odd]even.[end if]";</langsyntaxhighlight>
 
===other branching text substitutions===
Text that may be printed multiple times can also use sequential and random branching:
<langsyntaxhighlight lang="inform7">[a different color every time]
say "[one of]red[or]blue[or]green[at random].";
 
Line 3,047 ⟶ 3,415:
 
[only appears once]
say "[first time]Hello world![only]";</langsyntaxhighlight>
 
===rulebook approach===
Conditional logic may also be expressed in the form of a rulebook, with conditions on each rule:
 
<langsyntaxhighlight lang="inform7">Number Factory is a room.
 
Number handling is a number based rulebook with default success.
Line 3,064 ⟶ 3,432:
follow the number handling rules for 2;
follow the number handling rules for 4;
follow the number handling rules for 5.</langsyntaxhighlight>
 
=={{header|Isabelle}}==
<langsyntaxhighlight Isabellelang="isabelle">theory Scratch
imports Main
begin
Line 3,088 ⟶ 3,456:
lemma "recurse n = 0" by(induction n) simp+
 
end</langsyntaxhighlight>
 
=={{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===
<langsyntaxhighlight 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();
}</langsyntaxhighlight>
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
<langsyntaxhighlight lang="java">if (obj != null && obj.foo()) {
aMethod();
}</langsyntaxhighlight>
<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:
<langsyntaxhighlight lang="java">if (obj != null & obj.foo()) {
aMethod();
}</langsyntaxhighlight>
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:
<lang java>s.equals("Hello World") ? foo() : bar();</lang>
<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).
<langsyntaxhighlight lang="java">switch (c) {
case 'a':
foo();
break;
case 'b':
bar();
default:
foobar();
}</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="java">if (c == 'a') {
foo();
} else if (c == 'b') {
bar();
foobar();
} else {
foobar();
}</langsyntaxhighlight>
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,146 ⟶ 3,584:
===if-then-else===
 
<langsyntaxhighlight lang="javascript">if( s == "Hello World" ) {
foo();
} else if( s == "Bye World" ) {
Line 3,152 ⟶ 3,590:
} else {
deusEx();
}</langsyntaxhighlight>
 
===switch===
 
<langsyntaxhighlight lang="javascript">switch(object) {
case 1:
one();
Line 3,170 ⟶ 3,608:
default:
everythingElse();
}</langsyntaxhighlight>
 
===conditional (ternary) operator (?:)===
 
<langsyntaxhighlight lang="javascript">var num = window.obj ? obj.getNumber() : null;</langsyntaxhighlight>
 
The distinctive feature of the ternary operator (compared to JavaScript's other conditional structures) is that it evaluates as an expression rather than a statement, and can therefore be composed within larger expressions, making it a valuable resource of program structure in a functional idiom of JavaScript.
 
<langsyntaxhighlight JavaScriptlang="javascript">function takeWhile(lst, fnTest) {
'use strict';
var varHead = lst.length ? lst[0] : null;
Line 3,187 ⟶ 3,625:
) : []
) : [];
}</langsyntaxhighlight>
 
=={{header|JCL}}==
Line 3,200 ⟶ 3,638:
</pre>
The syntax of COND parameter of the EXEC statement is :
<langsyntaxhighlight lang="jcl"> COND=(rcval,relop,step)
relop is a relational opeator : EQ NE GT LT GE LE (= ¬= < > <= >=) </langsyntaxhighlight>
It is a condition to bypass a job step, and it can be translateted into :
<langsyntaxhighlight lang="jcl"> if rcval relop step.rc then not execute the current step </langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="jcl">//STEP6 EXEC PGM=MYPROG,COND=(0,NE,STEP3)</langsyntaxhighlight>
<pre>
if 0 ne STEP3.rc then skip step STEP6
Line 3,213 ⟶ 3,651:
</pre>
The conditions can be multiple :
<langsyntaxhighlight lang="jcl"> COND=((rcval1,relop1,step1),(rcval2,relop2,step2),...) </langsyntaxhighlight>
Means:
<langsyntaxhighlight lang="jcl"> if rcval1 relop1 step1.rc or rcval2 relop2 step2.rc or ... then not execute the current step </langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="jcl">//STEP6 EXEC PGM=MYPROG,COND=((4,LE,STEP1),(8,LE,STEP3)) </langsyntaxhighlight>
<pre>
if 4 le STEP1.rc or 8 le STEP3.rc then skip step STEP6
Line 3,228 ⟶ 3,666:
===if-then-else===
 
<langsyntaxhighlight lang="jinja">
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{% if loop.last %}.{% else %},{% endif %}
{%- endfor %}""").render())
</syntaxhighlight>
</lang>
 
===ternary expressions===
 
<langsyntaxhighlight lang="jinja">
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{{ "." if loop.last else "," }}
{%- endfor %}""").render())
</syntaxhighlight>
</lang>
 
===short-circuit evaluation===
 
<langsyntaxhighlight lang="jinja">
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{{ loop.last and "." or "," }}
{%- endfor %}""").render())
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
jq's main conditional construct is:<langsyntaxhighlight lang="jq">if cond then f else g end</langsyntaxhighlight>where cond, f, and g, are filters, and where cond may evaluate to anything at all, it being understood that:
# all JSON values are truthy except for false and null;
# if cond evaluates to nothing (i.e., produces an empty stream), then the entire if-then-else-end expression also produces an empty stream.
 
The general pattern allows one or more "elif _ then _" clauses:
<syntaxhighlight lang="jq">
<lang jq>
if cond then f elif cond1 then f1 .... else g end
</syntaxhighlight>
</lang>
 
For example:<langsyntaxhighlight lang="jq">
if empty then 2 else 3 end # produces no value
if 1 then 2 else 3 end # produces 2
if [false, false] then 2 else 3 end # produces 2
if (true, true) then 2 else 3 end # produces a stream: 2, 2
</langsyntaxhighlight>Notice that if cond produces a nonempty stream, then the entire expression will typically do the same. Since f and g also can produce streams, this lends itself to interesting Cartesian-product possibilities.
 
There is no "case <exp>" construct, but the idiom illustrated by the following example can be used to avoid the need to create a temporary variable to hold the "case" expression:<langsyntaxhighlight lang="jq">
exp
| if . == true then "true"
Line 3,274 ⟶ 3,712:
elif type == "string" then .
else error("unexpected value: \(.)")
end</langsyntaxhighlight>
Since jq's <tt>and</tt> and <tt>or</tt> are short-circuiting, they can also be used for branching, as can the binary disjunctive operator `//`.
 
Line 3,280 ⟶ 3,718:
Note: this documentation is mostly copied from the Julia 0.6.0 documentation at: https://docs.julialang.org/en/stable/manual/control-flow/#man-conditional-evaluation-1
<h3>Conditional Evaluation</h3>
<syntaxhighlight lang="julia">
<lang Julia>
function test(x, y)
if x < y
Line 3,299 ⟶ 3,737:
julia> test(1, 1)
x is equal to y
</syntaxhighlight>
</lang>
<p>
The elseif and else blocks are optional, and as many elseif blocks as desired can be used. The condition expressions in the if-elseif-else construct are evaluated until the first one evaluates to true, after which the associated block is evaluated, and no further condition expressions or blocks are evaluated.
</p><p>
The so-called "ternary operator", ?:, is closely related to the if-elseif-else syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:
</p><langsyntaxhighlight Julialang="julia">
a ? b : c
</syntaxhighlight>
</lang>
<p>
The expression a, before the ?, is a condition expression, and the ternary operation evaluates the expression b, before the :, if the condition a is true or the expression c, after the :, if it is false. To facilitate chaining, the operator associates from right to left.
Line 3,321 ⟶ 3,759:
=={{header|Kabap}}==
Kabap supports the '''if''' statement and a range of standard comparators. Truthiness is considered anything not "0" or 0.
<syntaxhighlight lang="kabap">
<lang Kabap>
if 1;
$result = "Execute";
Line 3,377 ⟶ 3,815:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Keg}}==
Keg supports if statements like this:
<langsyntaxhighlight lang="keg">?A>[The letter is larger than a|The letter is smaller than a]</langsyntaxhighlight>
Usually the ending proprotions may be omitted:
<langsyntaxhighlight lang="keg">?![You did enter something]</langsyntaxhighlight>
 
Also Keg supports (though not intentionally) a form of short-circuit evaluation:
<langsyntaxhighlight lang="keg">2?1>*# Returns 2 if the input is larger than 1</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 3,416 ⟶ 3,854:
}
println("$i is $t")
}</langsyntaxhighlight>
Sample input/output (program invoked without arguments):
{{out}}
Line 3,436 ⟶ 3,874:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{if true then yes else no}
-> yes
Line 3,454 ⟶ 3,892:
{switch 0}
-> 0 is zero
</syntaxhighlight>
</lang>
 
=={{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,463 ⟶ 3,901:
===if expressions===
If expressions are scoped per section.
<syntaxhighlight lang="langur">if .x == 0 {
<lang langur># using the fact 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,476 ⟶ 3,909:
val .y = 70
...
}</langsyntaxhighlight>
 
Prior to langur 0.10, you would use parentheses around the declared variable names (.alias, .name).
 
===shortened form if expression===
Line 3,485 ⟶ 3,916:
This is more flexible than a ternary operator, as it allows more than one test. An else section is optional (null by default).
 
<langsyntaxhighlight lang="langur">if(.x > .y: ...; .x < .y: ...; /* else */ ...)</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight lang="langur">if .x > .y: break</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight 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,504 ⟶ 3,952:
case _, null, true: ...
# .y == null and .z == true
}</langsyntaxhighlight>
 
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".
 
<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: ...
}</lang>
 
===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.
<langsyntaxhighlight lang="langur">givenswitch .x {
case true:
# implicit fallthrough
Line 3,534 ⟶ 3,964:
# no fallthrough
default: 1
}</langsyntaxhighlight>
 
===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.)
 
<lang langur>given .x {
<syntaxhighlight lang="langur">switch .x {
case true:
if .y > 100 {
Line 3,546 ⟶ 3,977:
}
case false: ...
}</langsyntaxhighlight>
 
===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).
<langsyntaxhighlight lang="langur">givenswitch(.x, .y, .z;
true: ... ; # allany are equal to true
_, >= .z: ...; # .y >= .z
... ) # default</langsyntaxhighlight>
 
=={{header|LC3 Assembly}}==
The LC3 sets condition codes (N[egative], Z[ero], and/or P[ositive]) based on the results of instructions that write values into the general purpose registers. The BR instruction utilizes these condition codes are to branch conditionally. If the BR instruction specifies one or more condition codes and at least one specified code is set, then the PC will be updated to the branch address. If none of the specified condition codes is set, then the next sequential instruction will execute. If the BR instruction does not specify any condition codes, then it is an unconditional branch, so the branch will be taken.
<langsyntaxhighlight lang="lc3asm">BR or BRnzp ; unconditional branch, i.e.
; branch if (result < 0 || result == 0 || result > 0)
; ^ this is always true
Line 3,566 ⟶ 3,997:
 
; or any combination of these condition codes, e.g.
BRnz ; branch if (result <= 0)</langsyntaxhighlight>
The effect of <tt>if (x == y) { go to LABEL }</tt> is achieved by adding <tt>x</tt> to <tt>-y</tt> (the two's complements of <tt>y</tt>) and branching if the result is zero. The following example prints "Branch Taken!" because the values of <tt>x</tt> and <tt>y</tt> are both 1.
<langsyntaxhighlight lang="lc3asm">.orig x3000
LD R1, x ; get x
LD R2, y ; get y
Line 3,586 ⟶ 4,017:
taken .stringz "Branch Taken!"
nottaken .stringz "Branch Not Taken!"
.end</langsyntaxhighlight>
 
=={{header|LIL}}==
LIL sports '''if''' with an optional code block for else conditions.
 
<langsyntaxhighlight lang="tcl">if {$a > 10} {print "code evaluated on true"}
if {$a > 10} {print "again"} {print "code evaluated on false"}</langsyntaxhighlight>
 
These can of course be nested in clear or nasty forms. '''if''' blocks can contain '''if''' blocks with as many optional else clauses as a programmer sees fit to intermingle.
Line 3,601 ⟶ 4,032:
{{works with|Lisaac|0.13.1}}
===if-then-else===
<langsyntaxhighlight Lisaaclang="lisaac">+ n : INTEGER;
 
n := 3;
Line 3,613 ⟶ 4,044:
} else {
IO.put_string "n is none of the above\n";
};</langsyntaxhighlight>
<langsyntaxhighlight Lisaaclang="lisaac">(n = 2).if_true { "n is 2\n".print; };
(n = 2).if_false { "n is not 2\n".print; };</langsyntaxhighlight>
===when===
<langsyntaxhighlight Lisaaclang="lisaac">+ n : INTEGER;
 
n := 3;
Line 3,629 ⟶ 4,060:
.when 4 then {
"n is 4\n".print;
};</langsyntaxhighlight>
There is no "else" or "otherwise" method.
If the values of the when-methods are overlapped, the related blocks will be evaluated ... they are not mutually exclusive.
Line 3,635 ⟶ 4,066:
=={{header|Little}}==
 
<langsyntaxhighlight Clang="c">int a = 3;
 
// if-then-else
Line 3,668 ⟶ 4,099:
default:
puts("is neither");
}</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">if :x < 0 [make "x 0 - :x]
 
ifelse emptyp :list [print [empty]] [print :list]</langsyntaxhighlight>
[[UCB Logo]] and its descendants have also case:
<langsyntaxhighlight lang="logo">to vowel? :letter
output case :letter [ [[a e i o u] "true] [else "false] ]
end
show vowel? "e
show vowel? "x</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="logo">true
false</langsyntaxhighlight>
Logo also provides TEST which is local to a procedure:
<langsyntaxhighlight lang="logo">to mytest :arg1 :arg2
test :arg1 = :arg2
iftrue [print [Arguments are equal]]
iffalse [print [Arguments are not equal]]
end</langsyntaxhighlight>
 
=={{header|LSE}}==
==={{header|SI..ALORS..SINON..FIN SI}}===
<langsyntaxhighlight LSElang="lse">SI A ET B ALORS
AFFICHER [4X, 'A ET B = .VRAI.',/]
SINON
Line 3,701 ⟶ 4,132:
SINON
AFFICHER [4X, 'A ET QUE B = .FAUX.',/]
FIN SI</langsyntaxhighlight>
 
==={{header|EVALUER}}===
<langsyntaxhighlight LSElang="lse">EVALUER X
QUAND 0
AFFICHER [4X,'QUAND X=0',/]
Line 3,713 ⟶ 4,144:
QUAND AUTRE
AFFICHER [4X,'QUAND X est autre, X=',U,/] X
FIN EVALUER</langsyntaxhighlight>
 
==={{header|SELON..ALLER EN..}}===
<langsyntaxhighlight LSElang="lse">0 AFFICHER [U,/] 'Faites votre choix:'
1 AFFICHER [8X,U,X,/] '0 VACHES'
2 AFFICHER [8X,U,/] '1 MOUTONS'
Line 3,723 ⟶ 4,154:
10 AFFICHER [U,/] 'Vous avez choisi VACHES!'
15 TERMINER
20 AFFICHER [U,/] 'Vous avez choisi MOUTONS!'</langsyntaxhighlight>
 
==={{header|SI..ALORS..SINON..IS}}===
<langsyntaxhighlight LSElang="lse">ENTIER U <- SI A ALORS 65535 SINON 1 IS</langsyntaxhighlight>
 
==={{header|SELON..DANS..SINON..FIN}}===
<langsyntaxhighlight LSElang="lse">ENTIER U <- SELON A DANS 0, 255 SINON 1 FIN</langsyntaxhighlight>
 
=={{header|LSE64}}==
The simple conditionals take single words rather than blocks of statements, as in most other languages.
<langsyntaxhighlight lang="lse64">t : " true" ,t
f : " false" ,t
true if t
false ifnot f
true ifelse t f</langsyntaxhighlight>
 
Cascading conditionals are constructed using duplicate definitions and "then", yielding a syntax reminiscent of functional language [[Pattern Matching]].
<langsyntaxhighlight lang="lse64">onetwo : drop " Neither one nor two" ,t # default declared first
onetwo : dup 2 = then " Two" ,t
onetwo : dup 1 = then " One" ,t</langsyntaxhighlight>
 
Short-circuit operators "&&" and "||" are used for complex conditionals.
<langsyntaxhighlight lang="lse64">dup 0 = || ,t # avoid printing a null string</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
--if-then-elseif-then-else
if a then
Line 3,780 ⟶ 4,211:
}
 
cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively</langsyntaxhighlight>
 
=={{header|Luna}}==
 
===if-then-else===
<langsyntaxhighlight lang="luna">if char == "<" then Prepend "<" acc else acc</langsyntaxhighlight>
''(see: [https://github.com/luna/luna/issues/125#issuecomment-365683922 github/luna #125])''
 
===case-of===
<langsyntaxhighlight lang="luna">class JSON:
...
def asText: case self of:
JSONString t: t
other: throw "JSON.asText: not a text"</langsyntaxhighlight>
 
''(see: [https://github.com/luna/luna/blob/77b1d974cb07528e9f195dd47e177dd497560da1/stdlib/Std/src/Base.luna#L1047-L1050 Std.JSON])''
Line 3,799 ⟶ 4,230:
=={{header|M2000 Interpreter}}==
===If Then Else.if Else===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Read a
Line 3,837 ⟶ 4,268:
CheckIt 0
CheckIt -100
</syntaxhighlight>
</lang>
 
===IF() and IF$() - Ternary===
One expression evaluated only. We can use If$() to use string expressions
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Read x
Line 3,858 ⟶ 4,289:
Checkit 3, 20
 
</syntaxhighlight>
</lang>
 
Ternary can used as Elvis operator (a function here), when a false (or a Nothing, for some kind of objects) evaluated then return something after ->, else return true or the object so if A is object then If(A->,B) return A.
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
def a
Line 3,876 ⟶ 4,307:
}
Checkit
</syntaxhighlight>
</lang>
 
===Select Case===
We can use string, and three types of cases (all of them in one case), >1000, 10 to 40, 400
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Read a
Line 3,922 ⟶ 4,353:
CheckIt -500
 
</syntaxhighlight>
</lang>
 
===Conditional loops===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
x=10
While x>0 {
Line 3,947 ⟶ 4,378:
Until x=10
 
</syntaxhighlight>
</lang>
 
===On Goto, On Gosub===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
For i=1 to 10 {
Line 3,981 ⟶ 4,412:
CheckIt
 
</syntaxhighlight>
</lang>
===If Then line No /label===
Line numbers are optional and can be in any order, but from start in current block, and if not found then replaced with exit, until search can't continue (at modules/function bounds, we can't jump out of a module or function).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
a$="123"
if a$ ~ "12*" then 1000
Line 3,993 ⟶ 4,424:
1000 Print "ok final"
Goto alfa
</syntaxhighlight>
</lang>
 
We can jump out of a sub, but we have to use Return to adjust the return stack.Wehn found Sub interpreter execute Exit statement so no need for End or Exit before sub beta()
Line 3,999 ⟶ 4,430:
We can call beta() using Gosub beta() (not Call, call is for modules and functions). If we have an array beta() then we must use Gosub beta() because interpreter prefer arrays, and raise error "missing ="
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Rem : Dim beta(10) ' remove Rem to get error when call beta() without Gosub
Line 4,020 ⟶ 4,451:
Checkit
 
</syntaxhighlight>
</lang>
 
=={{header|Make}}==
An if condition using pure make (no gmake extensions)
<langsyntaxhighlight lang="make"># make -f do.mk C=mycond if
C=0
 
Line 4,035 ⟶ 4,466:
 
false:
@echo "was false."</langsyntaxhighlight>
 
Using it
<langsyntaxhighlight lang="make">make -f do.mk if C=0
> was false.
 
make -f do.mk if C=1
> was true.</langsyntaxhighlight>
 
With out using recursion but letting make continue with non-failed
targets even when some of the targets failed (-k)
<langsyntaxhighlight lang="make">C=0
 
if: true false
Line 4,056 ⟶ 4,487:
false:
@expr $(C) >/dev/null && exit 1 || exit 0
@echo "was false."</langsyntaxhighlight>
 
Invoking it. Note the use of -k which allows make to evaluate subsequent
targets even when a previous non-related target failed.
<langsyntaxhighlight lang="make">|make -f do.mk -s -k C=1
was true.
*** Error code 1
|make -f do.mk -s -k C=0
*** Error code 1
was false.</langsyntaxhighlight>
 
Using gmake
 
<langsyntaxhighlight lang="make">A=
B=
 
Line 4,079 ⟶ 4,510:
 
do:
@echo $(A) .. $(B)</langsyntaxhighlight>
 
Using it
<langsyntaxhighlight lang="make">|gmake -f if.mk A=1
1 .. true
|gmake -f if.mk A=0
0 .. false</langsyntaxhighlight>
 
=={{header|Maple}}==
Line 4,092 ⟶ 4,523:
=== Conditional statements ===
Example syntax for conditional statements:
<langsyntaxhighlight Maplelang="maple">if x > 0 then
res := x;
else
res := -x;
end if;</langsyntaxhighlight>
 
Example syntax for conditional statements with else-if:
<langsyntaxhighlight Maplelang="maple">if x = 0 then
res := y;
elif y = 0 then
Line 4,105 ⟶ 4,536:
else
res := sqrt(x^2+y^2);
end if;</langsyntaxhighlight>
 
=== Conditional functions ===
Line 4,130 ⟶ 4,561:
===If statements===
Example:
<langsyntaxhighlight MATLABlang="matlab">if x == 1
disp 'x==1';
elseif x > 1
Line 4,136 ⟶ 4,567:
else
disp 'x<1';
end</langsyntaxhighlight>
===Switch statements===
Example:
<langsyntaxhighlight MATLABlang="matlab">switch x
case 1
disp 'Hello';
Line 4,146 ⟶ 4,577:
otherwise
disp 'Skynet Active';
end</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">if test1 then (...) elseif test2 then (...) else (...);</langsyntaxhighlight>
 
=={{header|MAXScript}}==
===if===
<langsyntaxhighlight lang="maxscript">if x == 1 then
(
print "one"
Line 4,164 ⟶ 4,595:
(
print "Neither one or two"
)</langsyntaxhighlight>
 
===case===
'''Form one'''
<langsyntaxhighlight lang="maxscript">case x of
(
1: (print "one")
2: (print "two")
default: (print "Neither one or two")
)</langsyntaxhighlight>
'''Form two'''
<langsyntaxhighlight lang="maxscript">case of
(
(x == 1): (print "one")
(x == 2): (print "two")
default: (print "Neither one or two")
)</langsyntaxhighlight>
 
=={{header|MBS}}==
 
<langsyntaxhighlight MBSlang="mbs">INT x;
x:=0;
IF x = 1 THEN
Line 4,190 ⟶ 4,621:
ELSE
! Do something else
ENDIF;</langsyntaxhighlight>
 
=={{header|MDL}}==
Line 4,200 ⟶ 4,631:
An "else" part is traditionally implemented as a final clause whose first element is an atom, like <code>T</code>, since atoms always evaluate to themselves and are always true.
 
<langsyntaxhighlight MDLlang="mdl"><COND (<==? .X 1> <PRINC "one">)
(<==? .X 2> <PRINC "two">)
(T <PRINC "something else">)></langsyntaxhighlight>
 
===AND and OR===
Line 4,208 ⟶ 4,639:
These short-circuiting boolean functions can also be used as simple conditionals.
 
<langsyntaxhighlight MDLlang="mdl">;"Negate X if its value is less than 0"
<AND <L? .X 0> <SET X <- .X>>>
 
;"Print a message unless the quiet flag is set"
<OR .QUIET? <PRINC "Finished">></langsyntaxhighlight>
 
=={{header|Metafont}}==
 
<langsyntaxhighlight lang="metafont">if conditionA:
% do something
elseif conditionB:
Line 4,223 ⟶ 4,654:
else:
% do this
fi;</langsyntaxhighlight>
 
The particularity of <tt>if</tt> construct in Metafont is that it can be part of an expression, and the "do something" <cite>does not need to fit into the syntactic structure</cite>. E.g. we can write something like
 
<langsyntaxhighlight lang="metafont">b := if a > 5: 3 + else: 2 - fi c;</langsyntaxhighlight>
 
Alone, the code <tt>3 +</tt> does not mean anything; but once the condition is evaluated, the whole expression must become "correct"; e.g. if <tt>a > 5</tt>, the expression will be
Line 4,236 ⟶ 4,667:
=={{header|min}}==
{{works with|min|0.19.6}}
<langsyntaxhighlight lang="min">(true) ("I'm true") ("I'm false") if ; If first quotation evaluates to true,
; evaluate second quotation.
; Otherwise, evaluate the third.
Line 4,247 ⟶ 4,678:
((3 <) ("Smaller than 3" puts!)) ; quotation if the first quotation
((true) ("Exactly 3" puts!)) ; evaluates to true. Otherwise, move
) case ; on to the next one.</langsyntaxhighlight>
 
=={{header|MiniScript}}==
MiniScript supports if/else-if/else, with arbitrary number of else-if sections when in block form:
 
<langsyntaxhighlight MiniScriptlang="miniscript">x = 42
if x < 10 then
print "small"
Line 4,261 ⟶ 4,692:
else
print "just right"
end if</langsyntaxhighlight>
 
It also supports single-line if or if/else statements (though no else-if sections are permitted in this case):
 
<langsyntaxhighlight MiniScriptlang="miniscript">x = 42
if x < 50 then print "small" else print "big"</langsyntaxhighlight>
 
Finally, like many other languages, MiniScript uses short-circuit evaluation, a form of implicit branching where the rest of a boolean expression is not evaluated at all if the truth value can already be determined.
 
<langsyntaxhighlight MiniScriptlang="miniscript">isSmall = function(x)
print "checking smallness"
return x < 40
Line 4,280 ⟶ 4,711:
end function
 
isSmall(10) or isBig(100)</langsyntaxhighlight>
 
{{out}}
<pre>checking smallness</pre>
 
=={{header|MIPS Assembly}}==
MIPS is a bit unusual in that it doesn't have "flags" per se. Every branch instruction takes one or more registers as an operand and does the comparison there.
===If/Else===
<syntaxhighlight lang="mips">BEQ $t0,$t1,Label ;branch to label if $t0 = $t1. If not, fallthrough to the instruction after the delay slot.
nop ;branch delay slot</syntaxhighlight>
 
The nice thing about this is, unlike most CISC architectures, you can make some important calculation that you'll use as a condition to branch, and before actually branching, do some other unrelated stuff without the CPU forgetting the correct way to branch. The following (rather contrived) example displays this idea in action:
 
<syntaxhighlight lang="mips">addu $t0,$t1 ;I'm going to branch based off this addition, but there's other things I want to do first.
lw $t3,($t4)
nop ;load delay slot
BEQ $t0,$t1,Label
nop ;branch delay slot</syntaxhighlight>
 
If you're wondering how a branch delay slot impacts the comparison, it doesn't. The delay slot instruction executes after the comparison has been made and CPU has decided whether to branch. (See [[MIPS Assembly]] for more info on what delay slots are.) As a result, code like this can introduce subtle off-by-one errors:
 
<syntaxhighlight lang="mips">BNEZ $t0,loop ;branch if $t0 is nonzero.
subiu $t0,1 ;this finishes at the same time the jumpback occurs.</syntaxhighlight>
 
MIPS also comes with greater than/less than constructs built-in.
* <code>BLT</code> <tt><</tt>
* <code>BLE</code> <tt><=</tt>
* <code>BGT</code> <tt>></tt>
* <code>BGE</code> <tt>>=</tt>
 
Adding a <code>U</code> to the end of any of the above makes the comparison unsigned. Remember, in assembly ''there are no signed/unsigned numbers, only signed/unsigned comparisons!''
 
<syntaxhighlight lang="mips">BGEU $t0,$t1,label ;branch if $t0 >= $t1, treating both as unsigned.
NOP
BLT $t7,$t3,label ;branch if $t7 < $t3, treating both as signed
NOP</syntaxhighlight>
 
Like most assembly languages, the label operand of a branch instruction is a hardware abstraction that allows you to more easily tell the assembler where you want the branch to go without having to figure it out yourself. In reality, the actual operand that the label represents is not an absolute address, but a calculated signed offset that is added to the program counter. Therefore there is a limit on how far away you can branch. Given that MIPS is a 32-bit CPU at a minimum, the maximum distance is very generous and you're extremely unlikely to ever need to branch further than it allows.
 
===Switch===
As usual, the easiest way to implement <code>switch</code> is with a lookup table, be it a table of function pointers or just a simple array. The example below is a bit abstract but you should get the idea.
 
<syntaxhighlight lang="mips">switchExample:
;this implementation assumes that all destinations end in jr ra, so you'll need to arrive here with JAL switchExample.
;$t0 = index (must be a multiple of 4 or the program counter will jump to a location that's not guaranteed to properly return.)
la cases,$t1
addiu $t1,$t0 ;MIPS can't do variable indexed offsetting so we have to add the offset ourselves.
lw $t8,($t1) ;dereference the pointer, $t8 contains the address we wish to "call"
nop
jr $t8 ;jump to the selected destination.
nop
 
cases:
.word foo
.word bar
.word baz
 
foo:
;code goes here
jr ra
 
bar:
;code goes here
jr ra
 
baz:
;code goes here
jr ra</syntaxhighlight>
 
If you're going to do this for real, you'll want some sort of bounds check on the index. That way, if the cases are out of bounds you can conditionally change the index to the address of your default case.
 
=={{header|МК-61/52}}==
Conditional jumps are done by four instructions, comparing the register X with zero:
 
<syntaxhighlight lang="text">x=0 XX
x#0 XX
x>=0 XX
x<0 XX</langsyntaxhighlight>
 
'''XX''' here is the address to which to make the jump in the event of failure of this condition (for this reason, these instructions are also called checks).
Line 4,297 ⟶ 4,794:
=={{header|Modula-2}}==
===if-then-else===
<langsyntaxhighlight lang="modula2">IF i = 1 THEN
InOut.WriteString('One')
ELSIF i = 2 THEN
Line 4,305 ⟶ 4,802:
ELSE
InOut.WriteString('Other')
END;</langsyntaxhighlight>
 
===Case===
<langsyntaxhighlight lang="modula2">CASE i OF
1 : InOut.WriteString('One')
| 2 : InOut.WriteString('Two')
Line 4,314 ⟶ 4,811:
ELSE
InOut.WriteString('Other')
END</langsyntaxhighlight>
 
=={{header|Modula-3}}==
===if-then-else===
<langsyntaxhighlight lang="modula3">IF Foo = TRUE THEN
Bar();
ELSE
Baz();
END;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="modula3">IF Foo = "foo" THEN
Bar();
ELSIF Foo = "bar" THEN
Line 4,332 ⟶ 4,829:
ELSE
Zeepf();
END;</langsyntaxhighlight>
 
===Case===
<langsyntaxhighlight lang="modula3">CASE Foo OF
| 1 => IO.Put("One\n");
| 2 => IO.Put("Two\n");
Line 4,341 ⟶ 4,838:
ELSE
IO.Put("Something\n");
END;</langsyntaxhighlight>
===Type-case===
<tt>TYPECASE</tt> is used on reference types to perform different operations, depending on what it is a reference to.
<langsyntaxhighlight lang="modula3">TYPECASE ref OF
| NULL => IO.Put("Null\n");
| CHAR => IO.Put("Char\n");
Line 4,350 ⟶ 4,847:
ELSE
IO.Put("Something\n");
END;</langsyntaxhighlight>
 
=={{header|Monicelli}}==
Monicelli has a single conditional structure that covers both if/then/else and switch/case
<langsyntaxhighlight lang="monicelli">
che cosè var? # switch var
minore di 0: # case var < 0
Line 4,363 ⟶ 4,860:
...
e velocità di esecuzione
</syntaxhighlight>
</lang>
 
=={{header|Morfa}}==
===if-then-else===
<langsyntaxhighlight lang="morfa">
if(s == "Hello World")
{
Line 4,378 ⟶ 4,875:
baz();
}
</syntaxhighlight>
</lang>
Morfa supports [[wp:Short-circuit_evaluation|short-circuit evaluation]], so <tt>obj.foo()</tt> won't be executed if <tt>obj</tt> is null:
<langsyntaxhighlight lang="morfa">
if(obj isnt null and obj.foo())
doSomething();
</syntaxhighlight>
</lang>
 
===ternary===
<langsyntaxhighlight lang="morfa">
var t = if(s == "Hello World") foo() else bar();
</syntaxhighlight>
</lang>
 
===switch===
There is no fallthrough, <tt>break</tt> statement does not have any special meaning inside a switch. If the <tt>break</tt> is in a loop then <tt>break</tt> exits that loop, otherwise it is invalid.
<langsyntaxhighlight lang="morfa">
switch (num)
{
Line 4,404 ⟶ 4,901:
result = "a lot";
}
</syntaxhighlight>
</lang>
 
=={{header|MUMPS}}==
===If / I and ELSE / E===
<syntaxhighlight lang MUMPS="mumps"> IF A list-of-MUMPS-commands</langsyntaxhighlight>
<p>All standard versions of MUMPS allow a ELSE command, which can be abbreviated to E. Instead of depending on the previous IF command, the ELSE command depends on the value of the system variable $TEST. $TEST is set whenever an IF command is executed, and whenever a timeout is specified. Since $TEST could be changed and not noticed by an unwary programmer it is important to remember when writing code.
 
For example with the code:
<langsyntaxhighlight MUMPSlang="mumps"> IF T DO SUBROUTINE
ELSE DO SOMETHING</langsyntaxhighlight>
It isn't clear whether $TEST is changed or not, because the function SUBROUTINE might change the value of $TEST by using a timeout or an IF command.
 
It is better to explicitly set the $TEST special variable using IF 1 for example:
<syntaxhighlight lang="mumps">
<lang MUMPS>
IF T DO SUBROUTINE IF 1
ELSE DO SOMETHING</langsyntaxhighlight>
 
Another common practice is to use the argumentless DO, as it pushes the $TEST variable onto a stack and replaces it after the "dot block" is complete. An example of this code is:
 
<syntaxhighlight lang="mumps">
<lang MUMPS>
IF T DO
. DO SUBROUTINE
ELSE DO SOMETHING</langsyntaxhighlight>
 
 
Line 4,432 ⟶ 4,929:
 
===$Select / $S===
<langsyntaxhighlight MUMPSlang="mumps"> WRITE $SELECT(1=2:"Unequal",1=3:"More unequal",1:"Who cares?")</langsyntaxhighlight>
<p>The $Select statement contains couplets separated by commas, which each consist of a conditional test, followed by a colon, and what to return if that condition is true.
The first part of the couplet must be a truth value. Since only zero is interpreted a truth value of false, any nonzero numbers when interpreted as a truth value will be considered to be true. Typically the number 1 is used as an explicitly true condition and is placed in the final couplet. If no conditions are true, the program's error processing is invoked. The very first condition that is true is the result of the expression. In the example, the value will always be "Unequal" as it is always true, and the rest of the $SELECT will never be used.</p>
 
===(command postconditional i.e. colon/:===
<langsyntaxhighlight MUMPSlang="mumps"> SET:(1=1) SKY="Blue"
GOTO:ReallyGo LABEL
QUIT:LoopDone
WRITE:NotLastInSet ","</langsyntaxhighlight>
<p>Most commands can take a "postconditional", which is a colon and some conditional statement immediately after the command followed by the command separator (space) and the usual arguments of the command. The command is executed only if the conditional statement evaluates to true.</p>
<p>The exceptions are FOR, IF, and ELSE.
Line 4,459 ⟶ 4,956:
=={{header|Nanoquery}}==
===if-then-else===
<langsyntaxhighlight lang="nanoquery">if x = 0
foo()
else if x = 1
Line 4,467 ⟶ 4,964:
else
boz()
end</langsyntaxhighlight>
 
=={{header|Nemerle}}==
===if-else===
<tt>if (cond) <then> else <this>;</tt> is an expression in Nemerle, requiring both keywords (<tt>if</tt> and <tt>else</tt>) to be valid. <tt>when</tt> and <tt>unless</tt> are macros for which <this> = null. <tt>cond</tt> must be an expression that evaluates to a bool (true|false), other types aren't automatically assigned truth or falsehood as in some languages.
<langsyntaxhighlight Nemerlelang="nemerle">if (the_answer == 42) FindQuestion() else Foo();
when (stock.price < buy_order) stock.Buy();
unless (text < "") Write(text);</langsyntaxhighlight>
 
===match===
Much cleaner than stacked if-else's, similar in some ways to switch-case (but more flexible). See [http://nemerle.org/wiki/index.php?title=Quick_Guide#Pattern_Matching here], [http://nemerle.org/wiki/index.php?title=Grok_Variants_and_matching#Matching here], or, for extra detail, [http://nemerle.org/wiki/index.php?title=Patterns_%28ref%29 the reference].
<langsyntaxhighlight Nemerlelang="nemerle">match(x)
{
|1 => "x is one"
|x when (x < 5) => "x is less than five"
|_ => "x is at least five"
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
===IF-THEN-ELSE===
<langsyntaxhighlight NetRexxlang="netrexx">-- simple construct
if logicalCondition then conditionWasTrue()
else conditionWasFalse()
Line 4,520 ⟶ 5,017:
conditionsWereFalse()
...
end</langsyntaxhighlight>
 
===SELECT===
Line 4,529 ⟶ 5,026:
 
<tt>OTHERWISE</tt> is optional but may result in run-time errors (<tt>netrexx.lang.NoOtherwiseException</tt>) if it isn't provided.
<langsyntaxhighlight NetRexxlang="netrexx">-- simple construct
select
when logicalCondition1 then condition1()
Line 4,544 ⟶ 5,041:
catch ex1 = NoOtherwiseException
ex1.printStackTrace()
end</langsyntaxhighlight>
 
===SELECT-CASE===
<langsyntaxhighlight NetRexxlang="netrexx">-- simple construct
select case cc
when 'A' then say 'the case is A'
when 'B' then say 'the case is B'
otherwise say 'selection not recognized'
end</langsyntaxhighlight>
 
'''Note:''' This is functionally equivalent to:
<langsyntaxhighlight NetRexxlang="netrexx">select
when cc == 'A' then ...
when cc == 'B' then ...
...</langsyntaxhighlight>
 
===SELECT Optional Features===
Line 4,571 ⟶ 5,068:
 
<tt>PROTECT</tt> is used for program concurrency &amp; synchonization in multi-threaded programs.
<langsyntaxhighlight NetRexxlang="netrexx">select label sl protect cc case cc
when 'A' then do
say 'the case is A'
Line 4,590 ⟶ 5,087:
say 'selection done'
say 'TTFN'
end sl</langsyntaxhighlight>
 
=={{header|newLISP}}==
===if===
'''Interpreter:''' [[newLISP]] v.9.0
<langsyntaxhighlight lang="lisp">(set 'x 1)
(if (= x 1) (println "is 1"))</langsyntaxhighlight>
A third expression can be used as an else.
<langsyntaxhighlight lang="lisp">(set 'x 0)
(if (= x 1) (println "is 1") (println "not 1"))</langsyntaxhighlight>
 
=={{header|Nim}}==
===if-then-else===
<langsyntaxhighlight lang="nim">if x == 0:
foo()
elif x == 1:
Line 4,610 ⟶ 5,107:
baz()
else:
boz()</langsyntaxhighlight>
 
===case-of===
<langsyntaxhighlight lang="nim">case x
of 0:
foo()
Line 4,621 ⟶ 5,118:
baz()
else: # All cases must be covered
boz()</langsyntaxhighlight>
 
=={{header|Objeck}}==
===if-else===
<langsyntaxhighlight lang="objeck">
a := GetValue();
if(a < 5) {
Line 4,636 ⟶ 5,133:
"equal to 5"->PrintLine();
};
</syntaxhighlight>
</lang>
 
===select===
<langsyntaxhighlight lang="objeck">
a := GetValue();
select(a) {
Line 4,654 ⟶ 5,151:
}
};
</syntaxhighlight>
</lang>
 
=={{header|Object Pascal}}==
Line 4,667 ⟶ 5,164:
===if-then-else===
 
<langsyntaxhighlight lang="ocaml">let condition = true
 
if condition then
1 (* evaluate something *)
else
2 (* evaluate something *)</langsyntaxhighlight>
 
If-then-else has higher precedence than <tt>;</tt> (the semicolon), so if you want to have multiple statements with side effects inside an "if", you have to enclose it with <tt>begin</tt>...<tt>end</tt> or with parentheses:
 
<langsyntaxhighlight lang="ocaml">if condition then begin
(); (* evaluate things for side effects *)
5
Line 4,683 ⟶ 5,180:
(); (* evaluate things for side effects *)
42
end</langsyntaxhighlight>
 
===match-with===
<langsyntaxhighlight lang="ocaml">match expression with
| 0 -> () (* evaluate something *)
| 1 -> () (* evaluate something *)
| n when n mod 2 = 0 -> () (* evaluate something *)
| _ -> () (* evaluate something *)</langsyntaxhighlight>
 
The first <tt>|</tt> is optional, and usually omitted.
Line 4,700 ⟶ 5,197:
=={{header|Octave}}==
'''if-then-elseif-else'''
<langsyntaxhighlight lang="octave">if (condition)
% body
endif
Line 4,716 ⟶ 5,213:
else
% otherwise body
endif</langsyntaxhighlight>
 
'''switch'''
<langsyntaxhighlight lang="octave">switch( expression )
case label1
% code for label1
Line 4,726 ⟶ 5,223:
otherwise
% none of the previous
endswitch</langsyntaxhighlight>
 
''Labels'' can be numeric or string, or cells to group several possibilities:
 
<langsyntaxhighlight lang="octave">switch ( x )
case 1
disp("it is 1");
Line 4,737 ⟶ 5,234:
otherwise
disp("unknown!");
endswitch</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 4,743 ⟶ 5,240:
Conditional structures are :
 
<langsyntaxhighlight Oforthlang="oforth">aBoolean ifTrue: [ ...]
aBoolean ifFalse: [ ... ]
aObject ifNull: [ ... ]
aObject ifNotNull: [ ... ]
aObject ifZero: [ ... ]</langsyntaxhighlight>
 
Each conditional structure consume the object on the top of the stack.
Each conditional structure can be followed by a else block
<syntaxhighlight lang Oforth="oforth">else: [ ... ]</langsyntaxhighlight>
 
Example :
 
<langsyntaxhighlight Oforthlang="oforth">Number virtual: sgn
self isPositive
ifTrue: [ self ==0 ifTrue: [ 0 ] else: [ 1 ] ]
else: [ -1 ] ;</langsyntaxhighlight>
 
=={{header|Ol}}==
if-then, the simplest conditional `if` primitive.
<langsyntaxhighlight 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>
</lang>
 
if-then-else, the full conditional '`if'` primitive.
<langsyntaxhighlight 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
</lang>
 
(if (= (* 2 2) 6)
unless, the opposite for 'if'.
(print "if-then-else: equal")
<lang scheme>
(unless (= (* 2 2) 4) (print "unlessif-then-else: non equal"))
; ==> if-then-else: non equal
(unless (= (* 2 2) 6) (print "unless: i don't know"))
</syntaxhighlight>
(unless (= (* 2 2) 4) (print "unless: non equal") (print "unless: equal"))
 
(unless (= (* 2 2) 6) (print "unless: i don't know") (print "unless: non equal"))
when and unless, the simplification of `if` without `begin`
; ==> unless: i don't know
<syntaxhighlight lang="scheme">
; ==> unless: equal
(when (= (* 2 2) 4)
; ==> unless: i don't know
(print "when: ..just do something..")
</lang>
(print "when: equal"))
; ==> when: ..just do something..
; ==> when: equal
 
(unless (= (* 2 2) 6)
(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>
 
case, the sequence of comparing values.
<langsyntaxhighlight 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
</lang>
 
; extended case with usable else
additionally, case can select vectors with variables filling
(case (* 2 2)
<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,811 ⟶ 5,359:
(else
(print "case: i don't know")))
; ==> tuple-case: selector 1, 2, 3
</syntaxhighlight>
</lang>
 
cond, the sequnce of comparators.
<langsyntaxhighlight lang="scheme">
(cond
((= (* 2 2) 4)
Line 4,824 ⟶ 5,372:
(print "cond: i don't know")))
; ==> cond: equal
</syntaxhighlight>
</lang>
 
case-lambda, selecting the lambda based on arguments count.
<langsyntaxhighlight lang="scheme">
(define smart (case-lambda
((x)
Line 4,838 ⟶ 5,386:
(smart 1 2) ; ==> 1, 2, -
(smart 1 2 3) ; ==> 1, 2, 3
</syntaxhighlight>
</lang>
 
=={{header|ooRexx}}==
Line 4,847 ⟶ 5,395:
may also be a list of conditional expressions separated by commas. The expressions are evaluated left-to-right, and evaluation
will stop with the first '0' result. For example,
<langsyntaxhighlight ooRexxlang="oorexx">if arg~isa(.string) & arg~left(1) == "*" then call processArg arg</langsyntaxhighlight>
 
would fail with a syntax error if the variable arg does not hold a string because the right-hand-side of the expression
is still evaluated. This can be coded as
 
<langsyntaxhighlight ooRexxlang="oorexx">if arg~isa(.string), arg~left(1) == "*" then call processArg arg</langsyntaxhighlight>
With this form, the second conditional expression is only evaluated if the first expression is true.
 
===IF THEN --- IF THEN/ELSE===
<syntaxhighlight lang="oorexx">
<lang ooRexx>
if y then x=6 /* Y must be either 0 or 1 */
 
Line 4,882 ⟶ 5,430:
else nop
else if z<0 then z=-y
</syntaxhighlight>
</lang>
 
===SELECT WHEN===
<syntaxhighlight lang="oorexx">
<lang ooRexx>
/*the WHEN conditional operators are the same as */
/*the IF conditional operators. */
Line 4,900 ⟶ 5,448:
/*were satisfiied, a SYNTAX condition is raised (error).*/
end
</syntaxhighlight>
</lang>
===SELECT WHEN/OTHERWISE===
<syntaxhighlight lang="oorexx">
<lang ooRexx>
select
when a=='angel' then many='host'
Line 4,917 ⟶ 5,465:
exit 13
end
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
if a then b=c else b=d
 
Line 4,942 ⟶ 5,490:
end select
 
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
===if-then-else===
<langsyntaxhighlight lang="oz">proc {PrintParity X}
if {IsEven X} then
{Show even}
Line 4,954 ⟶ 5,502:
{Show 'should not happen'}
end
end</langsyntaxhighlight>
 
===if-then-else as a ternary operator===
<langsyntaxhighlight lang="oz">fun {Max X Y}
if X > Y then X else Y end
end</langsyntaxhighlight>
 
===case statement===
<langsyntaxhighlight lang="oz">fun {Fac X}
case X of 0 then 1
[] _ then X * {Fac X-1}
end
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
GP uses a simple <code>if</code> statement:
<syntaxhighlight lang ="parigp">if(condition, do_if_true, do_if_false)</langsyntaxhighlight>
and short-circuit <code>&&</code> and <code>||</code> (which can be abbreviated <code>&</code> and <code>|</code> if desired).
 
Line 4,978 ⟶ 5,526:
===if-then-else===
 
<langsyntaxhighlight lang="pascal">IF condition1 THEN
procedure1
ELSE
Line 5,000 ⟶ 5,548:
procedure3;
procedure4
END;</langsyntaxhighlight>
 
=== case ===
Line 5,009 ⟶ 5,557:
In Pascal there is no fall-through to the next case. When execution reaches the end of a matching clause, it continues after the end of the case statement, not in the code for the next case.
 
<langsyntaxhighlight lang="pascal">case i of
1,4,9: { executed if i is 1, 4 or 9 }
DoSomething;
Line 5,018 ⟶ 5,566:
else
DoYetAnotherThing;
end;</langsyntaxhighlight>
 
Given the variable "X" as a char the following is valid:
 
<langsyntaxhighlight lang="pascal">Case X of
'A' : statement ;
'B' : statement ;
Line 5,028 ⟶ 5,576:
else
Statement ;
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 5,035 ⟶ 5,583:
===if/else===
 
<langsyntaxhighlight lang="perl">if ($expression) {
do_something;
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl"># postfix conditional
do_something if $expression;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">if ($expression) {
do_something;
}
else {
do_fallback;
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">if ($expression1) {
do_something;
}
Line 5,057 ⟶ 5,605:
else {
do_fallback;
}</langsyntaxhighlight>
 
===unless===
Line 5,069 ⟶ 5,617:
The ternary operator is used as an expression within a statement, rather than as a control flow structure containing one or more statements. It is frequently used in assignment, or sometimes for passing function call arguments that vary depending on some condition.
 
<langsyntaxhighlight lang="perl">$variable = $expression ? $value_for_true : $value_for_false;</langsyntaxhighlight>
 
===logical operators===
 
<langsyntaxhighlight lang="perl">$condition and do_something; # equivalent to $condition ? do_something : $condition</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">$condition or do_something; # equivalent to $condition ? $condition : do_something</langsyntaxhighlight>
 
<code>&&</code> and <code>||</code> have the same semantics as <code>and</code> and <code>or</code>, respectively, but their precedence is much higher, making them better for conditional expressions than control flow.
Line 5,085 ⟶ 5,633:
{{works with|Perl|5.10}}
 
<langsyntaxhighlight lang="perl">use feature "switch";
given ($input) {
when (0) { print 'input == 0'; }
Line 5,092 ⟶ 5,640:
when (/rats/) { print 'input matches rats'; }
default { do_fallback; }
}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
===if===
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">if</span> <span style="color: #000000;">name<span style="color: #0000FF;">=<span style="color: #008000;">"Pete"with</span> <span style="color: #008080;">thenjavascript_semantics</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"Pete"</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">age</span><span style="color: #0000FF;">></span><span style="color: #000000;">50</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">age</span><span style="color: #0000FF;"><</span><span style="color: #000000;">20</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">else</span>
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
 
There is no limit to the number of elsif clauses, including 0. The else clause is also optional,
Line 5,114 ⟶ 5,663:
 
===iff===
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #000000;">somevar</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff<span style="color: #0000FF;">(<span style="color: #000000;">flag<span style="color: #0000FF;">?<span style="color: #000000;">true_expr<span style="color: #0000FF;">:<span style="color: #000000;">false_expr<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
 
In an iff() expression, only one of true_expr or false_expr will be evaluated, not both.
Line 5,124 ⟶ 5,673:
first if statement, and in the second the conditions are evaluated at compile-time and code is only
emitted for one of the branches.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">DEBUG<span style="color: #0000FF;">=<span style="color: #004600;">false</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">DEBUG</span> <span style="color: #008080;">then</span>
Line 5,134 ⟶ 5,683:
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"this is linux\n"<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if
<!--</langsyntaxhighlight>-->
 
===switch===
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">switch</span> <span style="color: #000000;">v</span> <span style="color: #000080;font-style:italic;">/*with fallthrough*/</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">:</span>
Line 5,150 ⟶ 5,699:
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch
<!--</langsyntaxhighlight>-->
 
By default there is no fallthough on switch clauses, however you can add(/uncomment) a directive, and you can
Line 5,166 ⟶ 5,715:
use them, also have some conditional guards for cross-platform support
 
<syntaxhighlight lang="phix">without js -- (but maybe, at some point, and obviously that is as custom verbatim JavaScript code instead of assembly code)
<lang Phix>#ilASM{
#ilASM{
[32]
mov eax,[var]
Line 5,187 ⟶ 5,737:
syscall
[]
}</langsyntaxhighlight>
 
=={{header|PHL}}==
Line 5,193 ⟶ 5,743:
If-else:
 
<langsyntaxhighlight lang="phl">var a = 5;
if (a == 5) {
doSomething();
Line 5,200 ⟶ 5,750:
} else {
error();
}</langsyntaxhighlight>
 
=={{header|PHP}}==
Line 5,208 ⟶ 5,758:
'''Interpreter''': [[PHP]] 3.x, 4.x, 5.x
 
<langsyntaxhighlight lang="php"><?php
 
$foo = 3;
Line 5,229 ⟶ 5,779:
}
 
?></langsyntaxhighlight>
 
===switch===
Line 5,235 ⟶ 5,785:
'''Interpreter''': [[PHP]] 3.x & 4.x & 5.x
 
<langsyntaxhighlight lang="php"><?php
 
switch ($i)
Line 5,252 ⟶ 5,802:
}
 
?></langsyntaxhighlight>
 
===See Also===
Line 5,269 ⟶ 5,819:
Here are examples of each of these constructs.
 
<langsyntaxhighlight Picatlang="picat">go =>
N = 10,
 
Line 5,314 ⟶ 5,864:
% condition in function head
test_func(N) = "less than 14", N < 14 => true.
test_func(_N) = "not less than 14" => true. </langsyntaxhighlight>
 
{{out}}
Line 5,326 ⟶ 5,876:
=={{header|PicoLisp}}==
===Two-way conditions===
<langsyntaxhighlight PicoLisplang="picolisp">(if (condition) # If the condition evaluates to non-NIL
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
Line 5,334 ⟶ 5,884:
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(and-more) )</langsyntaxhighlight>
One-way conditions
<langsyntaxhighlight PicoLisplang="picolisp">(when (condition) # If the condition evaluates to non-NIL
(then-do-this) # Then execute tall following expressions
(and-more) )
Line 5,342 ⟶ 5,892:
(unless (condition) # If the condition evaluates to NIL
(then-do-this) # Then execute all following expressions
(and-more) )</langsyntaxhighlight>
===Four-way condition===
<langsyntaxhighlight PicoLisplang="picolisp">(if2 (condition1) (condition2) # If both conditions evaluate to non-NIL
(expression-both) # Then execute this expression
(expression-first) # Otherwise this for the first
(expression-second) # or this the second condition.
(expression-none) # If both are NIL, all following expressions
(and-more) )</langsyntaxhighlight>
===Multiple conditions===
<langsyntaxhighlight PicoLisplang="picolisp">(cond
((condition1) # If this condition evaluates to non-NIL
(expression 1) # Execute these expression(s)
Line 5,371 ⟶ 5,921:
(NIL # If none evaluated to NIL
(expression 1) # Execute these expression(s)
(more 1) )</langsyntaxhighlight>
 
===Selection===
<langsyntaxhighlight PicoLisplang="picolisp">(case (expression) # Evaluate the expression
(value1 # If it is equal to, or member of, 'value1'
(do-this1) # Execute these expression(s)
Line 5,382 ⟶ 5,932:
(do-that2) )
(T # Else execute final expression(s)
(do-something-else) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
===if-then-else===
<langsyntaxhighlight lang="pli">if condition_exp then unique_statement; else unique_statement;
 
if condition_exp then
Line 5,399 ⟶ 5,949:
else do;
list_of_statements;
end;</langsyntaxhighlight>
 
So a cascading form can be derived from:
<langsyntaxhighlight lang="pli">if condition_exp1 then
statement_1;
else if condition_exp2 then
Line 5,422 ⟶ 5,972:
else do;
list_of_statements;
end;</langsyntaxhighlight>
 
=== case ===
Line 5,428 ⟶ 5,978:
 
==== select - format 1 ====
<langsyntaxhighlight lang="pli">select (i); /* select on value of variable */
when (1,4,9)
do;
Line 5,443 ⟶ 5,993:
statement_s;
end;
end;</langsyntaxhighlight>
 
==== select - format 2 ====
<langsyntaxhighlight lang="pli">select; /* select first matching condition */
when (i = 4)
do;
Line 5,466 ⟶ 6,016:
statement_s;
end;
end;</langsyntaxhighlight>
 
Notes:
Line 5,476 ⟶ 6,026:
=={{header|PL/M}}==
IF-THEN-ELSE:
<langsyntaxhighlight lang="pli">/* IF-THEN-ELSE - THE ELSE STATEMENT; PART IS OPTIONAL */
IF COND THEN STATEMENT1; ELSE STATEMENT2;
 
Line 5,483 ⟶ 6,033:
ELSE IF CONB2 THEN STATEMENT2;
ELSE IF CONB3 THEN STATEMENT3;
ELSE STATEMENTX;</langsyntaxhighlight>
 
DO-CASE:
<langsyntaxhighlight lang="pli">/* CASE STATEMENT - EXECUTES STATEMENT0, STATEMENT1, ETC. */
/* DEPENDING ON WHETHER EXPR EVALUATES TO 0, 1, ... */
/* EXPR MUST BE IN RANGE OR THE PROGRAM WILL JUMP TO HYPERSPACE */
Line 5,493 ⟶ 6,043:
STATEMENT1;
...
END;</langsyntaxhighlight>
 
=={{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 5,499 ⟶ 6,058:
The simplest conditional is:
 
<langsyntaxhighlight lang="pop11">if condition then
;;; Action
endif;</langsyntaxhighlight>
 
Two way conditional looks like:
 
<langsyntaxhighlight lang="pop11">if condition then
;;; Action1
else
;;; Alternative action
endif;</langsyntaxhighlight>
 
One can do multiway choice using elseif clause
 
<langsyntaxhighlight lang="pop11">if condition1 then
;;; Action1
elseif condition2 then
Line 5,523 ⟶ 6,082:
else
;;; Alternative action
endif;</langsyntaxhighlight>
 
Instead of if keyword one can use unless keyword.
 
<langsyntaxhighlight lang="pop11">unless condition then /* Action */ endunless;</langsyntaxhighlight>
 
has the same meaning as
 
<langsyntaxhighlight lang="pop11">if not(condition) then /* Action */ endif;</langsyntaxhighlight>
 
One can also use elseunless keword.
 
<langsyntaxhighlight lang="pop11">if condition1 then
;;; Action1
elseunless condition2 then
Line 5,541 ⟶ 6,100:
endif;
;;; Action2
endif;</langsyntaxhighlight>
 
has the same meaning as
 
<langsyntaxhighlight lang="pop11">if condition1 then
;;; Action1
elseif not(condition2) then
;;; Action2
endif;</langsyntaxhighlight>
 
Note that conditional must end in matching keyword, if must be finished by endif, unless must be finished by endunless (in the
Line 5,556 ⟶ 6,115:
Pop11 conditional is an expression:
 
<langsyntaxhighlight lang="pop11">if x > 0 then 1 elseif x < 0 then -1 else 0 endif -> sign_x ;</langsyntaxhighlight>
 
assigns sign of x to sign_x.
Line 5,562 ⟶ 6,121:
Instead of multiway if one can use switchon construct (which is equivalent to a special case of if, but may be shorter).
 
<langsyntaxhighlight lang="pop11">switchon(x)
case .isstring then printf('A1');
notcase .isinteger then printf('A2');
Line 5,568 ⟶ 6,127:
case > 4 andcase < 15 then printf('A4');
else printf('A5');
endswitchon;</langsyntaxhighlight>
 
There is also multiway goto statement and conditional control transfers, we explain them together with other control transfers
Line 5,575 ⟶ 6,134:
Pop11 also has preprocessor allowing conditional compilation:
 
<langsyntaxhighlight lang="pop11">#_IF condition1
/* Variant 1 */
#_ELSEIF condition2
Line 5,581 ⟶ 6,140:
#_ELSE
/* Variant 3 */
#_ENDIF</langsyntaxhighlight>
 
condition1 and condition2 are arbitrary Pop11 expressions (they have access to all previously compiled code).
Line 5,591 ⟶ 6,150:
The "<tt>if</tt>" operator uses two items form the stack, a procedure and a boolean. It will execute the procedure if the boolean is true. It will not leave anything on the stack (but the procedure might):
 
<langsyntaxhighlight lang="postscript">9 10 lt {(9 is less than 10) show} if</langsyntaxhighlight>
 
The "<tt>ifelse</tt>" operator expects two procedures and executes the one or the other depending on the value of the boolean. I.e. this:
 
<langsyntaxhighlight lang="postscript">/a 5 lt {(yeah)} {(nope)} ifelse show</langsyntaxhighlight>
 
will render either the string "yeah" or "nope" depending on whether <tt>a</tt> is less than 5 or not.
Line 5,601 ⟶ 6,160:
=={{header|PowerShell}}==
===If, ElseIf, Else===
<langsyntaxhighlight lang="powershell"># standard if
if (condition) {
# ...
Line 5,620 ⟶ 6,179:
} else {
# ...
}</langsyntaxhighlight>
===Switch===
<langsyntaxhighlight lang="powershell"># standard switch
switch ($var) {
1 { "Value was 1" }
Line 5,651 ⟶ 6,210:
"\d+" { "Line started with a number" }
"\s+" { "Line started with whitespace" }
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 5,657 ⟶ 6,216:
A "pure" Prolog program by its very nature is one very long, very complicated boolean test. Absolutely every executable portion of Prolog is a test that succeeds or fails. Here are some examples, thus, of using conditionals in Prolog:
 
<langsyntaxhighlight Prologlang="prolog">go :- write('Hello, World!'), nl.</langsyntaxhighlight>
 
While operationally this looks like a program that when go/0 is executed will print "Hello, World!" and exit, it is actually a predicate, in the strict logical sense of the term, that tests conditions. Denotationally we'd describe it as "go/0 succeeds iff write/1 succeeds with its passed-in argument, and if nl/0 subsequently succeeds." (The fact that write/1 and nl/0 **always** succeed and that we use them for their side effects only doesn't matter to the Prolog view of a program.)
 
<langsyntaxhighlight Prologlang="prolog">fact(foo).
fact(bar).
fact(baz).
 
go :- fact(booger).
go :- fact(bar).</langsyntaxhighlight>
 
This example shows a few features of Prolog's testing and, specifically, shows nondeterminism and backtracking in action. In this we have a predicate fact/1 (so named because in this format, without an executable body, it is termed a "fact" in the literature). It has two clauses asserting both "bar" and "baz" as facts. go/0 also has two clauses. If we execute go/0, the runtime will tell us "true" (or, in some implementations, "yes") to indicate that the predicate call was successful. Denotationally we would say "fact(X) succeeds iff X unifies with foo, X unifies with bar, or X unifies with baz". We would also say "go/0 succeeds iff fact(booger) succeeds or if fact(bar) succeeds". When running, the first clause of go/0 will be executed and fact(booger) will be tested. fact(booger) does not match fact(bar) nor does it match fact(baz) so it fails. This leads the runtime to go back and try again with the **second** go/0 clause. In this one fact(bar) does, in fact, match fact(bar), so the overall test passes. A Prolog program is, thus, a very complicated tree of if/then statements, in effect.
 
<langsyntaxhighlight Prologlang="prolog">fact(X) :-
( X = foo
; X = bar
Line 5,677 ⟶ 6,236:
go :-
( fact(booger)
; fact(bar) ).</langsyntaxhighlight>
 
This version is semantically the same as the previous one. (In actual execution, because of some runtime optimizations, there are some minor differences in outcome, but nothing that would change the logical interpretation of the program.) Here we're showing more explicitly the various "or" conditions. In Prolog "," is roughly equivalent to "and" (conjunction) while ";" is roughly equivalent to "or" (disjunction). Because of this, and because of the fact we've taken separate clauses now and put them into explicit disjunctions it is clearer that we're performing a series of if/then tests in effect.
Line 5,683 ⟶ 6,242:
That being said, Prolog does have something that's very akin to real if/then statements (or, more accurately, similar to the ternary operator of languages like C):
 
<langsyntaxhighlight Prologlang="prolog">fact(X) :-
( X = bar -> write('You got me!'), nl
; write(X), write(' is not right!'), nl, fail ).
Line 5,689 ⟶ 6,248:
go :-
( fact(booger)
; fact(bar) ).</langsyntaxhighlight>
 
In this version of fact/1, the -> operator is used to perform a more traditional if/then/else. The general construct is ( condition -> succeed_branch ; fail_branch ). In this case if the parameter passed in unifies with 'bar', a message is written (recall that write/1 and nl/0 always succeed!) and the whole predicate exists with a success. If, on the other hand, the unification fails (you pass anything other than 'bar') it writes a snarky message and then calls fail/0, a predicate that, as its name suggests, always fails. There are more implications to using the conditional expression in Prolog; it is generally considered code smell. Other operators also exist for handling conditionals (like *->) that lack the "smell" of the conditional operator. The reasons for this are out of scope, however, for this article. Just know that the fact/1 predicate could have used *-> in place of -> and been more "sound" as a result.
Line 5,696 ⟶ 6,255:
{{works with|PureBasic|4.41}}
===If, Elseif, Else===
<langsyntaxhighlight PureBasiclang="purebasic">If a = 0
Debug "a = 0"
 
Line 5,705 ⟶ 6,264:
Debug "a < 0"
 
EndIf</langsyntaxhighlight>
 
===Select===
<langsyntaxhighlight PureBasiclang="purebasic">Variable = 2
 
Select Variable
Line 5,722 ⟶ 6,281:
Default
Debug "Variable = something else..."
EndSelect</langsyntaxhighlight>
 
===CompilerIf===
Compiler conditional structures works like normal conditional structures, except they are evaluated at compile time, and thus have to use constant expressions. Any defined constant can be used, these examples uses built-in constants.
<syntaxhighlight lang="purebasic">
<lang PureBasic>
CompilerIf #PB_Compiler_OS = #PB_OS_Linux And #PB_Compiler_Processor = #PB_Processor_x86
Debug "Compiled on x86 Linux"
Line 5,732 ⟶ 6,291:
Debug "Compiled on something else"
CompilerEndIf
</syntaxhighlight>
</lang>
 
===CompilerSelect===
<syntaxhighlight lang="purebasic">
<lang PureBasic>
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_Linux
Line 5,746 ⟶ 6,305:
Debug "Compiled on something else"
CompilerEndIf
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
===if-then-else===
 
<langsyntaxhighlight lang="python">if x == 0:
foo()
elif x == 1:
Line 5,758 ⟶ 6,317:
baz()
else:
boz()</langsyntaxhighlight>
 
===ternary expressions===
'''Interpreter:''' [[Python]] 2.5
 
<syntaxhighlight lang ="python">true_value if condition else false_value</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="python">>>> secret='foo'
>>> print 'got it' if secret=='foo' else 'try again'
'got it'</langsyntaxhighlight>
 
'''Note:''' this syntax is valid as an expression, the clauses cannot constain statements. The foregoing example is equivalent to:
 
<langsyntaxhighlight lang="python">>>> secret = 'foo'
>>> result = 'got it' if secret=='foo' else 'try again'
>>> print result
'got it'</langsyntaxhighlight>
 
===Function dispatch dictionary===
Line 5,781 ⟶ 6,340:
In some cases it's useful to associate functions with keys in a dictionary; and simply use this in lieu of long sequences of "if...elif...elif..." statements.
 
<langsyntaxhighlight lang="python">dispatcher = dict()
dispatcher[0]=foo # Not foo(): we bind the dictionary entry to the function's object,
# NOT to the results returned by an invocation of the function
Line 5,791 ⟶ 6,350:
# or with no "default" case:
if x in dispatcher:
results=dispatcher[x]()</langsyntaxhighlight>
 
<langsyntaxhighlight lang="python"># The above, but with a dict literal
dispatcher = {
0: foo,
Line 5,800 ⟶ 6,359:
}
# ...
results = dispatcher.get(x, boz)()</langsyntaxhighlight>
 
<langsyntaxhighlight lang="python"># Or without the temp variable
# (it's up to the reader to decide how "pythonic" this is or isn't)
results = {
Line 5,808 ⟶ 6,367:
1: bar,
2: baz,
}.get(x, boz)()</langsyntaxhighlight>
 
This can be particularly handy when using [[wp:Currying|currying]] techniques, or when lambda expressions or meta-function generators (factories) can be used in place of normal named functions.
 
In general a dispatch table or class/object abstraction (using dynamic method over-rides) is considered preferable to chains of ''if ... elif ... elif ...'' in Python programming.
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
 
Print "QB64/Qbasic conditional structures"
Dim k As String
Menu 1
View Print 13 To 23
Print "A menu example using the many options of IF statement"
k = " "
12: While k <> ""
k = UCase$(Input$(1))
If k = "O" GoTo O
If k = "F" Then 22
If k = "S" Then GoSub S: GoTo 12
If k = "C" Then GoSub 4: GoTo 12
If k = "E" Then GoSub 5: Exit While
Wend
Cls
Print "the same menu example with Select Case"
Sleep 2
While k <> ""
k = UCase$(Input$(1))
 
Select Case k
Case "O"
Print "You choose O"
Case "F"
Print "You choose F"
Case "S"
Print "You choose S"
Case "C"
Print "You choose C"
Case "E"
Print "You choose Exit"
_Delay 1
Exit While
Case Else
Print "Wrong choice"
End Select
Wend
View Print
Cls
Menu 2
View Print 13 To 23
Print "menu demonstration using ON value GOTO"
k = " "
While k <> ""
k = Input$(1)
On Val(k) GOSUB 1, 2, 3, 4, 5
Wend
End
 
1:
Print "Chosen O"
Return
 
2:
Print "Chosen F"
Return
 
3:
Print "Chosen S"
Return
 
4:
Print "Chosen C"
Return
 
5:
Print "Chosen E"
If k = "5" Then End
Return
 
 
O:
Print "You choose O"
GoTo 12
 
22:
Print "You choose F"
GoTo 12
 
S:
Print "You choose S"
Return
 
 
 
Sub Menu (Kind As Integer)
Locate 7, 33: Color 3, 4
Print "Choose the item"
Color 7, 0
Locate , 33
If Kind = 1 Then Print "Open a file"; Else Print "1) Open a file";
Color 14, 1
Locate , 33
If Kind = 1 Then Print "O" Else Print "1"
Color 7, 0
 
Locate , 33
If Kind = 1 Then Print "Find a file"; Else Print "2) Find a file";
Color 14, 1
Locate , 33
If Kind = 1 Then Print "F" Else Print "2"
Color 7, 0
 
Locate , 33
If Kind = 1 Then Print "Scan a file"; Else Print "3) Scan a file";
Color 14, 1
Locate , 33
If Kind = 1 Then Print "S" Else Print "3"
Color 7, 0
 
Locate , 33
If Kind = 1 Then Print "Copy a file"; Else Print "4) Copy a file";
Color 14, 1
Locate , 33
If Kind = 1 Then Print "C" Else Print "4"
Color 7, 0
 
Locate , 33
If Kind = 1 Then Print "Exit from Menu"; Else Print "5) Exit from Menu";
Color 14, 1
Locate , 33
If Kind = 1 Then Print "E" Else Print "5"
Color 7, 0
 
End Sub
</syntaxhighlight>
 
 
=={{header|Quackery}}==
Line 5,883 ⟶ 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}}==
===if===
Like most languages, R has an if statement as well as if-then-else:
<langsyntaxhighlight lang="rsplus">x <- 0
if(x == 0) print("foo")
x <- 1
if(x == 0) print("foo")
if(x == 0) print("foo") else print("bar")</langsyntaxhighlight>
{{out}}
<pre>> if(x == 0) print("foo")
Line 5,901 ⟶ 6,593:
===switch===
R also has switch, but it's a function rather than a special form of any sort. In fact, R has two versions of switch: one for numbers and one for characters.
<langsyntaxhighlight lang="rsplus">x <- 2
switch(x, print("Print if x == 1"), print("Print if x == 2"))</langsyntaxhighlight>
A notable part of the numeric version of switch is that, rounding and coercion aside, the cases must correspond exactly to the number of arguments given minus one. For example, the second argument of the switch statement will only be matched if the first argument equals (or is coerced to) 1 and the third argument will only do so for 2. There is no way to supply default cases or start from a number other than 1.
<langsyntaxhighlight lang="rsplus">x <- 3
switch(x, print("Print if x == 1"), print("Print if x == 2"))
x <- 2.7
switch(x, print("Print if x == 1"), print("Print if x == 2 or if there is rounding to 2"))</langsyntaxhighlight>
The other switch, the one that works for characters, is much more sensible. Its rules are clearly laid out in documentation, but rely on R's mechanisms for names, which makes them a little bit complicated. See [https://cran.r-project.org/doc/manuals/r-release/R-lang.html#switch the language definition] for a reasonably simple example.
<langsyntaxhighlight lang="rsplus">x <- "match"
switch(x, mat = 0, match = 10, other = 100, 1000)
x <- "ma"
switch(x, mat = 0, match = 10, other = 100, 1000)
x <- "foo"
switch(x, mat = 0, match = 10, other = 100, 1000)</langsyntaxhighlight>
{{out}}
<pre>> switch(x, print("Print if x == 1"), print("Print if x == 2"))
Line 5,935 ⟶ 6,627:
 
Note also that it is not a ternary operator and its documentation warns against using it as such. In my experience, its most common use is in recoding data. For example:
<langsyntaxhighlight lang="rsplus">data <- c(1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0)
ifelse(data == 1, "Yes", "No")</langsyntaxhighlight>
{{out}}
<pre>> ifelse(data == 1, "Yes", "No")
Line 5,945 ⟶ 6,637:
===[http://docs.racket-lang.org/reference/if.html#%28form._%28%28quote._~23~25kernel%29._if%29%29 if]===
If-expressions in Racket must have both branches
<langsyntaxhighlight lang="racket">
(if (< x 10)
"small"
"big")
</syntaxhighlight>
</lang>
 
===[http://docs.racket-lang.org/reference/when_unless.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29 when/unless]===
One-sided conditional expressions use "when" and "unless". These are more convenient for side-effects since they have an implicit "begin" around their body, and you can also include new definitions
<langsyntaxhighlight lang="racket">
(when (< x 10)
(define y (* x 10))
(printf "small\n"))
</syntaxhighlight>
</lang>
 
===[http://docs.racket-lang.org/reference/if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29 cond]===
Used for multiple conditions:
<langsyntaxhighlight lang="racket">
(printf "x is ~a\n"
(cond [(< x 1) "tiny"]
Line 5,969 ⟶ 6,661:
[(< x 100000000) "huge"]
[else "gigantic"]))
</syntaxhighlight>
</lang>
 
===[http://docs.racket-lang.org/reference/case.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29 case]===
Similar to a "switch" statement in other languages
<langsyntaxhighlight lang="racket">
(case x
[(1) "one"]
Line 5,982 ⟶ 6,674:
[(5 7 9) "odd"]
[else "something else"])
</syntaxhighlight>
</lang>
 
===etc===
Line 5,994 ⟶ 6,686:
</li><li> <tt>unless</tt> no longer permits <tt>elsif</tt> or <tt>else</tt> blocks.
</li><li> If the block of an <tt>if</tt>, <tt>elsif</tt>, or <tt>unless</tt> has a nonzero arity, the value of the conditional expression is used as an argument to the block:
<syntaxhighlight lang="raku" perl6line>if won() -> $prize {
say "You won $prize.";
}</langsyntaxhighlight>
If an <tt>else</tt> block has a nonzero arity, it receives the value of the condition tested by the last <tt>if</tt> or <tt>elsif</tt>. </li></ul>
===given/when===
Switch structures are done by topicalization and by smartmatching in Raku. They are somewhat orthogonal, you can use a <tt>given</tt> block without <tt>when</tt>, and vice versa. But the typical use is:
<syntaxhighlight lang="raku" perl6line>given lc prompt("Done? ") {
when 'yes' { return }
when 'no' { next }
default { say "Please answer either yes or no." }
}</langsyntaxhighlight>
<tt>when</tt> blocks are allowed in any block that topicalizes <tt>$_</tt>, including a
<tt>for</tt> loop (assuming one of its loop variables is bound to <tt>$_</tt>)
or the body of a method (if you have declared the invocant as <tt>$_</tt>)." See [more at: https://designdocs.raku.org/S04.htmllanguage/control#Switch_statements Synopsis 4].index-entry-switch_(given)
 
There are also statement modifier forms of all of the above.
Line 6,013 ⟶ 6,705:
===Ternary operator===
The [[wp:ternary operator|ternary operator]] looks like this:
<syntaxhighlight lang="raku" perl6line>$expression ?? do_something !! do_fallback</langsyntaxhighlight>
 
===Other short-circuiting operators===
Line 6,021 ⟶ 6,713:
===If-Either-Case-Switch===
If the result is true, the block! will be evaluated. If false nothing happens.
<langsyntaxhighlight Redlang="red">>> if 10 > 2 [print "ten is bigger"]
ten is bigger</langsyntaxhighlight>
===EITHER===
If the result is true the first block! will be evaluated.
If false the second block! will be evaluated.
<langsyntaxhighlight Redlang="red">>> either 3 > 2 [print "Three larger"][print "Nope!"]
Three larger</langsyntaxhighlight>
===CASE===
The block! following the first true condition is evaluated.
<langsyntaxhighlight Redlang="red">n: 50
case [
n < 10 [print "small number"]
Line 6,051 ⟶ 6,743:
medium number
large number
none of these</langsyntaxhighlight>
 
===SWITCH===
<langsyntaxhighlight Redlang="red">switch "india" [
"a" [print "string"]
23 [print "integer"]
Line 6,070 ⟶ 6,762:
]
 
no match</langsyntaxhighlight>
 
=={{header|Retro}}==
===choose, if, and -if===
<langsyntaxhighlight Retrolang="retro">condition [ true statements ] if
condition [ false statements ] -if
condition [ true statements ] [ false statements ] choose</langsyntaxhighlight>
 
These forms can be used interactively, or inside function definitions.
 
===when===
<langsyntaxhighlight Retrolang="retro">:foo (n-)
#1 [ ( if quote evaluates to true ) ] case
#2 [ ( if quote evaluates to true ) ] case
#3 [ ( if quote evaluates to true ) ] case
drop ( default action ) ;</langsyntaxhighlight>
 
=={{header|REXX}}==
===IF--THEN, IF--THEN--ELSE===
<langsyntaxhighlight lang="rexx">if y then @=6 /* Y must be either 0 or 1 */
 
if t**2>u then x=y /*simple IF with THEN & ELSE. */
Line 6,106 ⟶ 6,798:
substr(abc,4,1)=='~' then if z=0 then call punt
else nop /*NOP pairs up IF*/
else if z<0 then z=-y /*alignment helps*/</langsyntaxhighlight>
 
===SELECT--WHEN===
<langsyntaxhighlight lang="rexx"> /*the WHEN conditional operators are the same as*/
/*the IF conditional operators. */
select
Line 6,132 ⟶ 6,824:
when a=='wolf' then many='pack'
otherwise many='?'
end /*2nd select*/ /* [↑] uses OTHERWISE as a catch-all.*/</langsyntaxhighlight>
 
===SELECT--WHEN/OTHERWISE===
<langsyntaxhighlight lang="rexx"> select
when g=='angel' then many='host'
when g=='ass' | g=='donkey' then many='pace'
Line 6,148 ⟶ 6,840:
say
exit 13
end /*select*/</langsyntaxhighlight>
 
=={{header|Rhope}}==
{{works with|Rhope|alpha 1}}
===if-then-else===
<langsyntaxhighlight lang="rhope">If[cond]
|:
Do Something[]
:||:
Do Something Else[]
:|</langsyntaxhighlight>
 
=={{header|Ring}}==
'''if-but-else-ok'''
<langsyntaxhighlight lang="ring">If x == 1
SomeFunc1()
But x == 2
Line 6,168 ⟶ 6,860:
Else
SomeFunc()
Ok</langsyntaxhighlight>
 
'''Switch'''
<langsyntaxhighlight lang="ring">Switch x
On 1
SomeFunc1()
Line 6,178 ⟶ 6,870:
Other
SomeFunc()
Off</langsyntaxhighlight>
 
=={{header|RLaB}}==
Line 6,184 ⟶ 6,876:
=== if ===
Block of instructions following the ''if'' command has to be always enclosed in curly brackets.
<syntaxhighlight lang="rlab">
<lang RLaB>
if (x==1)
{
// do something
}
</syntaxhighlight>
</lang>
 
=== if-else ===
Line 6,195 ⟶ 6,887:
Consider an example:
 
<syntaxhighlight lang="rlab">
<lang RLaB>
if (x==1)
{
Line 6,204 ⟶ 6,896:
y = sin(const.pi*(1-x)) / (1-x);
}
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="rlab">
<lang RLaB>
if (x==1)
{
Line 6,219 ⟶ 6,911:
y = rand();
}}
</syntaxhighlight>
</lang>
 
=={{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,225 ⟶ 6,934:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">' Boolean Evaluations
'
' > Greater Than
Line 6,304 ⟶ 7,013:
print "color unknown"
 
end select</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 6,310 ⟶ 7,019:
====Conditional compilation====
Rust supports conditional compilation via the `cfg` annotation.
<langsyntaxhighlight lang="rust">// This function will only be compiled if we are compiling on Linux
#[cfg(target_os = "linux")]
fn running_linux() {
Line 6,331 ⟶ 7,040:
))]
fn highly_specific_function() {}
</syntaxhighlight>
</lang>
Conditional compilation may also be achieved via the `cfg!` macro.
<langsyntaxhighlight lang="rust">fn main() {
if cfg!(target_os = "linux") {
// Do something
}
}</langsyntaxhighlight>
 
====Generics (static dispatch)====
By default, generics in Rust are monomorphized, so no vtable lookups at runtime are necessary.
<langsyntaxhighlight lang="rust">trait PrintType {
fn print_type(&self);
}
Line 6,368 ⟶ 7,077:
prints_type_of_args(&'a', &2.0);
prints_type_of_args(&'a', &'b');
}</langsyntaxhighlight>
 
===Runtime===
====If-statement====
<langsyntaxhighlight lang="rust">if some_conditional {
do_stuff();
} else if some_other_conditional {
Line 6,392 ⟶ 7,101:
// Do something with x_coord and y_coord
}
}</langsyntaxhighlight>
 
====Match statement====
Match statements are essentially more powerful switch statements
<langsyntaxhighlight lang="rust">fn some_other_function(p: Option<Point>) {
match p {
Some(Point { x: 0, y: 0 }) => println!("Point is on origin"),
Line 6,405 ⟶ 7,114:
None => println!("We didn't get a point"),
}
}</langsyntaxhighlight>
 
====Generics (dynamic dispatch)====
Generics may also be accomplished via dynamic dispatch, so the actual code that is run is determined at compile time.
Using the same trait defined in the static dispatch section:
<langsyntaxhighlight lang="rust">fn prints_args_dynamic(arg1: &PrintType, arg2: &PrintType) {
arg1.print_type();
arg2.print_type();
Line 6,417 ⟶ 7,126:
prints_args_dynamic(&'a', &2.0);
prints_args_dynamic(&6.3,&'c');
}</langsyntaxhighlight>
 
=={{header|Sather}}==
 
<langsyntaxhighlight lang="sather"> if EXPR then
-- CODE
elsif EXPR then
Line 6,427 ⟶ 7,136:
else
-- CODE
end;</langsyntaxhighlight>
 
EXPR must evaluate to BOOL (true or false); <code>elsif</code> and <code>else</code> are optional.
 
<langsyntaxhighlight lang="sather"> case EXPR
when EXPRL then
-- CODE
Line 6,438 ⟶ 7,147:
else
-- CODE
end;</langsyntaxhighlight>
 
EXPRL is a single expression or a comma-separated list of exressions. The expressions must evaluate to comparable objects (the method <code>is_eq</code> must be implemented)
Line 6,444 ⟶ 7,153:
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala"> if (n == 12) "twelve" else "not twelve"
today match {
Line 6,454 ⟶ 7,163:
Accumulate_Sales
case _ => {}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 6,461 ⟶ 7,170:
===Primitive===
====if====
<syntaxhighlight lang="text">(if <test> <consequent> <alternate>)</langsyntaxhighlight>
<syntaxhighlight lang="text">(if <test> <consequent>)</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="scheme">(display
(if (> 1 2)
"yes"
Line 6,472 ⟶ 7,181:
(if (> 1 2)
(- 1 2)))
(newline)</langsyntaxhighlight>
{{out}}
<pre>no
Line 6,479 ⟶ 7,188:
===Derived===
====cond====
<syntaxhighlight lang="text">(cond <clause1> <clause2> ...)</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="scheme">(display
(cond ((> 1 2) "greater")
((< 1 2) "less")))
Line 6,489 ⟶ 7,198:
((< 1 1) "less")
(else "equal")))
(newline)</langsyntaxhighlight>
{{out}}
<pre>less
Line 6,495 ⟶ 7,204:
 
====case====
<syntaxhighlight lang="text">(case <key> <clause1> <clause2> ...)</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="scheme">(display
(case (* 2 3)
((2 3 5 7) "prime")
Line 6,507 ⟶ 7,216:
((w y) "semivowel")
(else "consonant")))
(newline)</langsyntaxhighlight>
{{out}}
<pre>composite
Line 6,532 ⟶ 7,241:
There can be single or multiple statements.
An if-statement can have multiple elsif parts.
<langsyntaxhighlight lang="seed7">if condition then
statement
end if;
Line 6,554 ⟶ 7,263:
else
statement3;
end if;</langsyntaxhighlight>
 
=== case ===
<langsyntaxhighlight lang="seed7">case i of
when {1, 4, 9}: # Executed if i is 1, 4 or 9
statement1;
Line 6,566 ⟶ 7,275:
otherwise:
statement4;
end case;</langsyntaxhighlight>
 
=={{header|SIMPOL}}==
===if-else if-else===
<langsyntaxhighlight lang="simpol">if x == 1
foo()
else if x == 2
Line 6,576 ⟶ 7,285:
else
foobar()
end if</langsyntaxhighlight>
 
===ternary if function===
<langsyntaxhighlight lang="simpol">.if(x == 1, "hello", "world")</langsyntaxhighlight>
 
=={{header|Simula}}==
Line 6,589 ⟶ 7,298:
'''if''' X=Y '''then''' K:=I
An example:
<langsyntaxhighlight lang="simula">BEGIN
INTEGER i,j;
i:=1; j:=2;
Line 6,607 ⟶ 7,316:
END;
OutImage
END</langsyntaxhighlight>
Simula 67 has also a switch structure:
declaration::= '''switch''' switch:=list_of labels
statement::= '''goto''' switch[expression]
An example:
<langsyntaxhighlight lang="simula">BEGIN
INTEGER i,j;
SWITCH target:=L1,L2,L3;
Line 6,622 ⟶ 7,331:
L3: OutText("CC");
OutImage
END</langsyntaxhighlight>
 
=={{header|Slate}}==
===ifTrue/ifFalse===
<langsyntaxhighlight lang="slate">"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)"
balance > 0
ifTrue: [inform: 'still sitting pretty!'.]
ifFalse: [inform: 'No money till payday!'.].</langsyntaxhighlight>
 
 
===caseOf:otherwise:===
<langsyntaxhighlight lang="slate">c@(Net URLPathEncoder traits) convert
[ | byte1 byte2 byte3 digit1 digit2|
[c in isAtEnd] whileFalse:
Line 6,647 ⟶ 7,356:
} otherwise: [c out nextPut: byte1].
].
].</langsyntaxhighlight>
 
===whileTrue:/whileFalse:===
 
<langsyntaxhighlight lang="slate">[p isAtEnd] whileFalse: [p next evaluate]].</langsyntaxhighlight>
 
=={{header|Slope}}==
 
The following examples are highly derived, but should give the basics. All of the forms below (if, case, cond) return the result of evaluating their associated expression/consequent. The examples below tend toward side effects, so mostly return the empty list.
 
===if===
 
Syntax:
<syntaxhighlight lang="text">(if [test] [consequent] [[alternate]])</syntaxhighlight>
 
Example:
 
<syntaxhighlight lang="slope">(define my-file (file-open-read "my-file.txt"))
(if my-file (write (read-all my-file)) (! "Could not open file"))</syntaxhighlight>
 
===case===
 
Syntax:
<syntaxhighlight lang="text">(case [value] (match-val expression)...)</syntaxhighlight>
 
Example:
<syntaxhighlight lang="slope">
(case my-enum
(string (do-string my-enum))
(bool (do-bool my-enum))
(proc (my-enum))
(number (do-number my-enum))
(else (! "No match found in case")))</syntaxhighlight>
 
===cond===
 
Syntax:
<syntaxhighlight lang="text">(cond ([test] [expression])...)</syntaxhighlight>
 
Example:
<syntaxhighlight lang="slope">(define my-num 123)
(cond
((positive? my-num) 'positive)
((negative? my-num) 'negative)
(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 6,667 ⟶ 7,447:
Conditionals in Smalltalk are really messages sent to Boolean objects.
<br>The most basic conditional is the ifTrue/ifFalse, which is defined in 4 variants in the Boolean class &sup1; (the receiver is the following examples is a boolean, which get the alternative code pieces as argument):
<langsyntaxhighlight lang="smalltalk">
balance > 0
ifTrue: [Transcript cr; show: 'still sitting pretty!'.]
Line 6,679 ⟶ 7,459:
ifFalse:[ self gotoHappyHour ]
ifTrue:[ self noDrinksToday ].
</syntaxhighlight>
</lang>
 
You can also use them as the ternary operator
 
<langsyntaxhighlight lang="smalltalk">abs := x > 0 ifTrue: [ x ] ifFalse: [ x negated ]</langsyntaxhighlight>
 
Or get the alternatives from somewhere else (for example, passed as parameter)
 
<langsyntaxhighlight lang="smalltalk">...
trueAction := [ ... do something ].
falseAction := [ ... do something else ...].
...
abs := x > 0 ifTrue:trueAction ifFalse:falseAction. "3)"</langsyntaxhighlight>
 
Note &sup1; strictly speaking, these are methods (aka virtual functions) in the subclasses of Boolean (True and False) if which true and false are singletons. Thus, conditional execution is actually implemented via polymorphism, in that those methods either do or do not evaluate their argument (or one of the alternatives). The compiler will optimize and inline special cases (i.e. boolean receivers).
Line 6,698 ⟶ 7,478:
 
===Switch Case===
<langsyntaxhighlight lang="smalltalk">|x|
x := 1.
value :=
Line 6,706 ⟶ 7,486:
[3]->['three']
}
otherwise:['none of them'].</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
SNOBOL4 has no structured programming features, but the two constructs in question could be easily emulated with FAILURE/SUCCESS and indirect jumps
 
<langsyntaxhighlight lang="snobol"> A = "true"
* "if-then-else"
if A "true" :s(goTrue)f(goFalse)
Line 6,724 ⟶ 7,504:
default output = "A is neither FALSE nor TRUE"
esac
end</langsyntaxhighlight>
 
=={{header|SNUSP}}==
 
<langsyntaxhighlight lang="snusp">$==?\==zero=====!/==#
\==non zero==/</langsyntaxhighlight>
 
'''?''' is the only conditional operator. It skips one character if the current cell is zero.
Line 6,743 ⟶ 7,523:
If statement:
 
<langsyntaxhighlight lang="sparkling">var odd = 13;
if odd % 2 != 0 {
print("odd");
}</langsyntaxhighlight>
 
If-else statement:
 
<langsyntaxhighlight lang="sparkling">var odd = 13;
if odd % 2 != 0 {
print("odd");
} else {
print("even");
}</langsyntaxhighlight>
 
If and if-else statements can be chained:
 
<langsyntaxhighlight lang="sparkling">var nodiv3 = 13;
if nodiv3 % 3 == 0 {
print("divisible by 3");
Line 6,766 ⟶ 7,546:
} else {
print("gives 2 remainder");
}</langsyntaxhighlight>
 
There's no "switch-case" statement in Sparkling yet, but it's work in progress.
Line 6,773 ⟶ 7,553:
{{works with|MS SQL|2005}}
===Conditional Expression===
<langsyntaxhighlight lang="sql">case when a then b else c end
 
declare @n int
Line 6,781 ⟶ 7,561:
--If/ElseIf expression
set @n=5
print case when @n=3 then 'Three' when @n=4 then 'Four' else 'Other' end</langsyntaxhighlight>
 
===If/Else===
<langsyntaxhighlight lang="sql">declare @n int
set @n=123
if @n=123
Line 6,792 ⟶ 7,572:
ELSE
if @n=124 print 'one two four'
else print 'other'</langsyntaxhighlight>
 
=={{header|SSEM}}==
The SSEM's only conditional operation is <tt>011 Test</tt>, which causes the computer to skip the next instruction if the value held in the accumulator is negative. This program illustrates it: assuming address 10 stores a variable, we test whether its negation is negative (i.e. whether the variable itself is positive). If it is, we skip the next instruction and proceed with the program; but, if it is not negative (i.e. the variable is negative or zero), we jump to address 1 + the value stored at address 14. It is easy to see how this can be used to implement loops, other conditional tests, etc.
<langsyntaxhighlight lang="ssem">01010000000000100000000000000000 -10 to c
00000000000000110000000000000000 Test
01110000000000000000000000000000 14 to CI</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 6,804 ⟶ 7,584:
This is an equivalent of a ternary ?: in C, useful for instance when creating a variable with '''[https://www.stata.com/help.cgi?generate gen]'''. See '''[https://www.stata.com/help.cgi?cond cond]''' in Stata help.
 
<langsyntaxhighlight lang="stata">clear
set obs 4
gen a = cond(mod(_n, 2)==1, "A", "B")
Line 6,814 ⟶ 7,594:
| A |
| B |
+---+</langsyntaxhighlight>
 
=== if command ===
This one is mainly useful in programs. See '''[https://www.stata.com/help.cgi?ifcmd ifcmd]''' in Stata help. To illustrate the command, here is a program that checks if a number is prime.
 
<langsyntaxhighlight lang="stata">program isprime
sca n = `0'
sca p = 1
Line 6,852 ⟶ 7,632:
 
isprime `=10^12-11'
999999999989 is prime.</langsyntaxhighlight>
 
=== if expression ===
When used in a command, '''[https://www.stata.com/help.cgi?if if]''' means the command is to be applied to the data subset for which the if expression is true.
 
<langsyntaxhighlight lang="stata">clear
set obs 100
count
100
count if mod(_n, 3)==0
33</langsyntaxhighlight>
 
=== if statement in Mata ===
See [https://www.stata.com/help.cgi?%5bM-2%5d%20if Stata help]. Here is an equivalent of the above program to check if a number is prime.
 
<langsyntaxhighlight lang="stata">function isprime(n) {
if (n<5) return(n==2 | n==3)
else if (mod(n, 2)==0) return(0)
Line 6,879 ⟶ 7,659:
 
isprime(10^12-11)
1</langsyntaxhighlight>
 
=== ternary operator in Mata ===
Line 6,885 ⟶ 7,665:
See [https://www.stata.com/help.cgi?m2_op_conditional Stata help]. Here is a recursive implementation of the Fibonacci sequence, to illustrate.
 
<langsyntaxhighlight lang="stata">function fib(n) {
return(n<2 ? n : fib(n-1)+fib(n-2))
}
 
fib(10)
55</langsyntaxhighlight>
 
=={{header|Swahili}}==
===if-else if-else (kama-au-sivyo)===
<langsyntaxhighlight lang="swahili">kama (kweli) {
andika("statement")
} au (kweli /* condition */) {
Line 6,902 ⟶ 7,682:
} sivyo {
andika("statement")
}</langsyntaxhighlight>
 
=={{header|Tailspin}}==
Tailspin has only one true conditional structure, a set of matchers. Each templates (sort of a function that takes one input value and emits zero or more outputs) has a set of matchers. If it only has matchers, they are invoked. If the templates has a
block, the matchers are invoked by sending to them (by "-> #"). The matchers can also be used as a looping structure by sending values back to be matched (also by "-> #").
<langsyntaxhighlight lang="tailspin">
templates foo
when <=0> do 'zero' -> !OUT::write
Line 6,916 ⟶ 7,696:
otherwise 'odd' -> !OUT::write
end foo
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
 
===if-then-else===
<langsyntaxhighlight lang="tcl">if {$foo == 3} {
puts "foo is three"
} elseif {$foo == 4} {
Line 6,927 ⟶ 7,707:
} else {
puts "foo is neither three nor four"
}</langsyntaxhighlight>
or (using the ternary operator of expressions)
<langsyntaxhighlight lang="tcl">set result [expr { $foo == 3 ? "three" : "not three" }]</langsyntaxhighlight>
 
===switch===
<langsyntaxhighlight lang="tcl">switch -- $foo {
3 {puts "foo is three"}
4 {puts "foo is four"}
default {puts "foo is something else"}
}</langsyntaxhighlight>
Note that the <tt>switch</tt> command can also use glob matching (like <tt>case</tt> in the Bourne Shell) or regular-expression matching.
 
Line 6,944 ⟶ 7,724:
 
===If Statement===
<langsyntaxhighlight lang="tern">if(a > b)
println(a);</langsyntaxhighlight>
 
===If Else Statement===
<langsyntaxhighlight lang="tern">if(a > b) {
println(a);
} else {
println(b);
}</langsyntaxhighlight>
 
===Unless Statement===
<langsyntaxhighlight lang="tern">unless(a > b) {
println(b);
} else {
println(a);
}</langsyntaxhighlight>
 
===Switch Statement===
<langsyntaxhighlight lang="tern">switch(a) {
case 10:
case 11:
Line 6,969 ⟶ 7,749:
default:
println(b);
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 6,976 ⟶ 7,756:
'''Basic form'''
<br> with only one statement for the true part:
<langsyntaxhighlight lang="ti83b">If condition
statement</langsyntaxhighlight>
or in one line
<syntaxhighlight lang ="ti83b">If condition : statement</langsyntaxhighlight>
 
'''If-Then form'''
<langsyntaxhighlight lang="ti83b">If condition
Then
statements
End</langsyntaxhighlight>
 
'''If-Then-Else form'''
<langsyntaxhighlight lang="ti83b">If condition
Then
statements
Else
statements
End</langsyntaxhighlight>
 
=={{header|Toka}}==
Line 7,000 ⟶ 7,780:
( condition ) ( quote ) ifTrue
 
<langsyntaxhighlight lang="toka">100 100 = [ ." True\n" ] ifTrue
100 200 = [ ." True\n" ] ifTrue</langsyntaxhighlight>
 
===ifFalse===
( condition ) ( quote ) ifFalse
 
<langsyntaxhighlight lang="toka">100 100 = [ ." True\n" ] ifFalse
100 200 = [ ." True\n" ] ifFalse</langsyntaxhighlight>
 
===ifTrueFalse===
( condition ) ( true quote ) ( false quote ) ifTrueFalse
 
<langsyntaxhighlight lang="toka">100 100 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse
100 200 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse</langsyntaxhighlight>
 
=={{header|TorqueScript}}==
Line 7,019 ⟶ 7,799:
===if-then-else===
 
<langsyntaxhighlight lang="tqs">// numbers and objects
if(%num == 1)
{
Line 7,045 ⟶ 7,825:
{
deusEx();
}</langsyntaxhighlight>
 
===switch===
 
<langsyntaxhighlight lang="tqs">// numbers and objects
switch(%num)
{
Line 7,077 ⟶ 7,857:
default:
somethingElse();
}</langsyntaxhighlight>
 
===conditional (ternary) operator (?:)===
 
<langsyntaxhighlight lang="tqs">%formatted = %str @ ((getSubStr(%str,strLen(%str) - 1,1) $= "s") ? "'" : "'s");</langsyntaxhighlight>
 
 
=={{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}}==
===branch===
<langsyntaxhighlight lang="trith">true ["yes" print] ["no" print] branch</langsyntaxhighlight>
===when===
<langsyntaxhighlight lang="trith">true ["yes" print] when</langsyntaxhighlight>
===unless===
<langsyntaxhighlight lang="trith">false ["no" print] unless</langsyntaxhighlight>
 
 
=={{header|True BASIC}}==
<langsyntaxhighlight lang="basic">
! IF-ELSEIF-ELSE-END IF
! SELECT-CASE
Line 7,128 ⟶ 7,939:
 
ON expresión Gosub label1, label2 ELSE label3
</syntaxhighlight>
</lang>
 
=={{header|TUSCRIPT}}==
===IF ELSEIF ELSE ENDIF===
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 7,143 ⟶ 7,954:
---> do something
ENDIF
</syntaxhighlight>
</lang>
===SELECT CASE DEFAULT ENDSELECT===
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 7,160 ⟶ 7,971:
---> do something
ENDSELECT
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
Line 7,172 ⟶ 7,983:
For instance the <code>choose</code> construct will select, from among those clauses which match successfully, the one which maximizes or minimizes the length of an extracted variable binding:
 
<langsyntaxhighlight lang="txr">
@(choose :shortest x)
@x:@y
Line 7,179 ⟶ 7,990:
@(or)
@x+@y
@(end)</langsyntaxhighlight>
 
Suppose the input is something which can match all three patterns in different ways:
Line 7,198 ⟶ 8,009:
For instance:
 
<langsyntaxhighlight lang="txr">@(all)
@x:y@
@z<-@w
Line 7,205 ⟶ 8,016:
We have a match: (x, y, z, w) = (@x, @y, @z, @w).
@(end)
@(end)</langsyntaxhighlight>
 
If any subclause fails to match, then <code>all</code> stops processing subsequent clauses. There are subtleties though, because an earlier clause can produce variable bindings which are visible to later clauses.
If previously bound variable is bound again, it must be to an identical piece of text:
 
<langsyntaxhighlight lang="txr">@# match a line which contains some piece of text x
@# after the rightmost occurence of : such that the same piece
@# of text also occurs at the start of the line preceded by -->
Line 7,217 ⟶ 8,028:
@(and)
-->@x@/.*/
@(end)</langsyntaxhighlight>
 
<pre>$ echo "-->asdfhjig:asdf" | txr -B weird.txr -
Line 7,233 ⟶ 8,044:
The basic syntax is <code>if ''command-list''; then ''command-list''; fi</code>. If the first command list succeeds (by returning 0 for success), then the shell runs the second command list.
 
<langsyntaxhighlight lang="sh">if test 3 -lt 5; then echo '3 is less than 5'; fi</langsyntaxhighlight>
 
==== Else and elif ====
Line 7,239 ⟶ 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
fi</syntaxhighlight>
echo '4 compares not to 6'
fi</lang>
 
==== Switch conditionals ====
Line 7,251 ⟶ 8,061:
The Unix shell provides support for multibranch switch conditional constructs using the case statement:
 
<langsyntaxhighlight lang="sh">case value in
choicea)
foo
Line 7,258 ⟶ 8,068:
bar
;;
esac</langsyntaxhighlight>
 
==== Conditional branching using operators ====
Line 7,264 ⟶ 8,074:
One can also use <code>&&</code> and <code>||</code> as conditional structures; see [[short-circuit evaluation#UNIX Shell]].
 
<langsyntaxhighlight lang="sh">test 3 -lt 5 && echo '3 is less than 5'
test 4 -ge 6 || echo '4 is not greater than or equal to 6'</langsyntaxhighlight>
 
==== Conditional loops ====
Line 7,271 ⟶ 8,081:
The Unix shell also supports conditional loops:
 
<langsyntaxhighlight lang="sh"># This is a while loop
l=1
while [ l -le 5 ]; do
Line 7,281 ⟶ 8,091:
until [ l -eq 5 ]; do
echo $l
done</langsyntaxhighlight>
 
==={{header|C Shell}}===
The single-line <code>if</code> syntax is <code>if (''expression'') ''simple-command''</code>.
 
<langsyntaxhighlight lang="csh">if (3 < 5) echo '3 is less than 5'
if ({ grep -q ^root: /etc/passwd }) echo 'passwd has root'</langsyntaxhighlight>
 
The multi-line <code>if</code> syntax has a <code>then</code> clause, and can have optional <code>else if</code> and <code>else</code> clauses. Each clause may contain multiple commands.
 
<langsyntaxhighlight lang="csh">if (4 >= 6) then
echo '4 is greater than or equal to 6'
else if (4 < 6) then
Line 7,297 ⟶ 8,107:
else
echo '4 compares not to 6'
endif</langsyntaxhighlight>
 
=={{header|Unison}}==
<langsyntaxhighlight Unisonlang="unison">factorial : Nat -> Nat
factorial x =
if x == 0 then 1
else
x * fac (Nat.drop x 1)</langsyntaxhighlight>
 
=={{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}}==
===ifThenElse===
<langsyntaxhighlight lang="v">[true]
['is true' puts]
['is false' puts]
ifte
 
=is true</langsyntaxhighlight>
 
===ifThen===
<langsyntaxhighlight lang="v">[true]
['is true' puts]
if
=is true</langsyntaxhighlight>
 
===When===
<langsyntaxhighlight lang="v">3 [
[1 =] [1 *]
[2 =] [10 *]
Line 7,329 ⟶ 8,149:
] when
 
=300</langsyntaxhighlight>
===Choice===
<langsyntaxhighlight lang="v">true
1 2
choice
Line 7,341 ⟶ 8,161:
choice
 
=2</langsyntaxhighlight>
 
=={{header|VBA}}==
===If Else End If===
<syntaxhighlight lang="vb">
<lang vb>
Sub C_S_If()
Dim A$, B$
Line 7,370 ⟶ 8,190:
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub</langsyntaxhighlight>
 
===If ElseIf Else End If===
<langsyntaxhighlight lang="vb">Sub C_S_ElseIf()
Dim A$, B$
 
Line 7,388 ⟶ 8,208:
Debug.Print A & " < " & B
End If
End Sub</langsyntaxhighlight>
===Select Case===
<langsyntaxhighlight lang="vb">Sub C_S_Select_Case()
'With Strings
Dim A$, C&
Line 7,441 ⟶ 8,261:
Debug.Print "C >= 20"
End Select
End Sub</langsyntaxhighlight>
===Inline IF===
<langsyntaxhighlight lang="vb">Sub C_S_IIF()
Dim myName
myName = 2
Line 7,449 ⟶ 8,269:
'return : Justin
End Sub
</syntaxhighlight>
</lang>
===Switch===
<langsyntaxhighlight lang="vb">Sub C_S_Switch()
Dim myName
myName = 2
Line 7,457 ⟶ 8,277:
'return : Justin
End Sub
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
===if-then-else===
Block form:
<langsyntaxhighlight lang="vb">If condition1 Then
statement
End If
Line 7,476 ⟶ 8,296:
statement
End If
</syntaxhighlight>
</lang>
Line form:
<langsyntaxhighlight lang="vb">If condition Then statement
 
If condition Then statement Else statement</langsyntaxhighlight>
===select-case===
<langsyntaxhighlight lang="vb">Select Case Expression
Case Value1: statement
Case Value2: statement
Line 7,500 ⟶ 8,320:
Case Else
statements
End Select</langsyntaxhighlight>
 
=={{header|Verbexx}}==
<langsyntaxhighlight lang="verbexx">@VAR a b = 1 2;
 
// -------------------------------------------------------------------------------------
Line 7,572 ⟶ 8,392:
n = 0 @CASE results: n == 0(1)
n = 1 @CASE results: n == 1(2c)
n = 2 @CASE results: else</langsyntaxhighlight>
 
 
=={{header|Verilog}}==
===if-else===
<syntaxhighlight lang="verilog">
<lang Verilog>
if( expr_booleana ) command1;
else command2;
</syntaxhighlight>
</lang>
 
===case===
<syntaxhighlight lang="verilog">
<lang Verilog>
case( expr_booleana )
valor1: command1;
Line 7,590 ⟶ 8,410:
default: commandN;
endcase
</syntaxhighlight>
</lang>
 
 
Line 7,596 ⟶ 8,416:
===if-then-else===
====Block form====
<langsyntaxhighlight lang="vb">If condition Then
statement
End If
Line 7,615 ⟶ 8,435:
Else
statement
End If</langsyntaxhighlight>
 
====Line form====
<langsyntaxhighlight lang="vb">If condition Then statement
 
If condition Then statement Else statement</langsyntaxhighlight>
 
===select-case===
<langsyntaxhighlight lang="vb">Select Case Expression
Case Value1: statement
Case Value2: statement
Line 7,642 ⟶ 8,462:
statements
End Select
</syntaxhighlight>
</lang>
===inline if-then-else===
<langsyntaxhighlight lang="vb">IIf(expr, then-value, else-value)</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="vbnet"> myName = 2
Debug.Print IIf(myName = 1, "John", "Jack")
'return : "Jack")</langsyntaxhighlight>
 
===inline switch===
<langsyntaxhighlight lang="vb">Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n,value-n]])</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="vb"> myName = 2
Debug.Print Switch(myName = 1, "James", myName = 2, "Jacob", myName = 3, "Jeremy")
'return : "Jacob"</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 7,661 ⟶ 8,481:
===if-then-else===
''Basic''
<langsyntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"
 
If a = b Then
Line 7,667 ⟶ 8,487:
Else
result = "failed"
End If</langsyntaxhighlight>
 
''Condensed''
<langsyntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"
 
If a = b Then result = "passed" Else result = "failed"
Line 7,682 ⟶ 8,502:
Else
result = "failed"
End If</langsyntaxhighlight>
 
===if-then-elseif===
<langsyntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"
 
If a = b Then
Line 7,693 ⟶ 8,513:
Else
result = "impossible"
End If</langsyntaxhighlight>
 
===select-case-else===
<langsyntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"
 
Select Case a
Line 7,704 ⟶ 8,524:
Case Else
result = "impossible"
End Select</langsyntaxhighlight>
 
===inline-conditional===
<langsyntaxhighlight lang="vbnet">Imports Microsoft.VisualBasic
 
...
Line 7,713 ⟶ 8,533:
Dim result As String = CType(IIf("pants" = "glasses", "passed", "failed"), String) 'VB 1-8
 
Dim result As String = If("pants" = "glasses", "passed", "failed") 'VB 9</langsyntaxhighlight>
 
===generic-inline-conditional===
{{works with|Visual Basic .NET|8.0}}
<langsyntaxhighlight lang="vbnet">Imports Microsoft.VisualBasic
 
...
Line 7,727 ⟶ 8,547:
...
 
Dim result As String = IIf2("pants" = "glasses", "passed", "failed") ' type is inferred</langsyntaxhighlight>
 
===generic-inline-conditional===
'''Language Version:''' 9.0+
 
<langsyntaxhighlight lang="vbnet">Dim result As String = If("pants" = "glasses", "passed", "failed") ' type is inferred</langsyntaxhighlight>
 
=={{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 {
other
statements
}</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 {
otherStatements
}
</syntaxhighlight>
 
===Match===
Simple usage is,
<syntaxhighlight lang="v (vlang)">match true {
boolean_expression1 {
statements
}
boolean_expression2 {
other
statements
}
else {
last
resort
statements
}
}</syntaxhighlight>
Because match can work with any number of arbitrary boolean expressions, it replaces if/elseif chains often found in other programming languages.
 
Match can also switch on the value of an expression, as in,
<syntaxhighlight lang="v (vlang)">switch expression_of_any_type {
value1 {
statements
}
value2, value3, value4 {
other
statements
}
else {}
}</syntaxhighlight>
As shown, multiple values can be listed for a single case clause.
Since vlang is statically typed, the types of value1, 2, 3, and 4 must match the type of the expression.
 
=={{header|Vorpal}}==
 
===if-then-else===
<langsyntaxhighlight lang="vorpal">if(condition){
result = 'met'
}
else{
result = 'not met'
}</langsyntaxhighlight>
 
=={{header|Woma}}==
Line 7,749 ⟶ 8,623:
===break-if===
Valid inside of a <@> (loop) block.
<syntaxhighlight lang ="woma"><%>condition</langsyntaxhighlight>
 
===continue-if===
Valid inside of a <@> (loop) block.
<syntaxhighlight lang ="woma"><$>condition</langsyntaxhighlight>
 
===if statement===
Valid inside of a function or a <@> (loop) block.
<langsyntaxhighlight lang="woma">condition = True
condition<?>print(condition)</langsyntaxhighlight>
 
=={{header|Wrapl}}==
Line 7,764 ⟶ 8,638:
===simple conditional===
Conditionals in Wrapl are expressions. Either success or failure can be omitted from the expression.
<langsyntaxhighlight lang="wrapl">condition => success // failure
condition => success
condition // failure</langsyntaxhighlight>
 
===goal directed evaluation===
Wrapl's goal directed evaluation can be used to control conditional execution.
The select-right operator <tt>&</tt> produces the values of the right operand for each value produced by the left operand. Thus if the left operand fails to produce any values, the right operand is never evaluated.
<syntaxhighlight lang ="wrapl">condition & success</langsyntaxhighlight>
The sequence operator <tt>|</tt> produces the values of the left operand followed by the values of the right operand. Thus if the left operand produces enough values (for example in a context where only one value is required), the right operand is never evaluated.
<syntaxhighlight lang ="wrapl">condition | failure</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight ecmascriptlang="wren">for (b in [true, false]) {
if (b) {
System.print(true)
Line 7,794 ⟶ 8,668:
 
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 7,813 ⟶ 8,687:
===ifs/elseifs/elses===
Assembly doesn't work on if/else if/else statements(Unless you're using MASM or alike assemblers:)). Rather, it has conditional jumps which work off flags set by the comparison. Take this general statement from C.
<syntaxhighlight lang="c">
<lang c>
if(i>1)
DoSomething
 
FailedSoContinueCodeExecution.
</syntaxhighlight>
</lang>
There are actually a number of ways to implement that in assembly. The most typical way would be something like..
<langsyntaxhighlight lang="asm">
cmp i, 1
jg _DoSomething
FailedSoContinueCodeExecution
</syntaxhighlight>
</lang>
Using the "jg" instruction,our code will jump to _DoSomething if the comparison(cmp i,1) made our ZF(ZeroFlag) flag well, zero. Which means only 1 thing. It is in fact greater than. In contrast, if i is in fact equal or less than 1, ZF is set to 1. The Zero Flag will remain set as long as we don't use any instructions that alter flags(comparisons for example). So, here's another C example
<syntaxhighlight lang="c">
<lang c>
if(i>1)
DoSomething
Line 7,832 ⟶ 8,706:
DoSomethingElse
FailedSoContinueCodeExecution
</syntaxhighlight>
</lang>
In this case, we can use our previous example as a skeleton.
<langsyntaxhighlight lang="asm">
cmp i, 1
jg _DoSomething
jle _DoSomethingElse
FailedSoContinueCodeExecution
</syntaxhighlight>
</lang>
This does another state check on the Zero flag(actually jg/jle also check another flag, but that's not overly important) using jle. JumpifLessthanorEqual. Essentially, jle jumps if ZG is set to 1. So, it's jump condition is the opposite to jg.<br>
<br>
One last commonly used condition.
<syntaxhighlight lang="c">
<lang c>
if(i==1)
DoSomething
Line 7,849 ⟶ 8,723:
DoSomethingElse
FailedSoContinueExecution
</syntaxhighlight>
</lang>
 
In this case, we'd do this.
<langsyntaxhighlight lang="asm">
cmp i, 1
je _DoSomething
jne _DoSomethingElse
FailedSoContinueExecution
</syntaxhighlight>
</lang>
The je/jne jump instructions are again like jg/jle opposites of each other and again like je/jne rely on how the zero flag is set in the previous comparison. <br>
There are many different conditional jumps in assembly and many ways to set them, test, and, or to name a few. The ones covered are just some commonly used ones in order to show how assembly deals with conditional statements.
Line 7,864 ⟶ 8,738:
===If===
An <code>IF</code> expression has the form <code>(IF <condition> <then-clause> <opt-else-clause>)</code>, for example:
<langsyntaxhighlight lang="lisp">(if (eq s "Rosetta Code")
"The well-known programming chrestomathy site"
"Some other website, maybe, I dunno" )</langsyntaxhighlight>
If the condition evaluates to anything except <code>NIL</code> or the empty list (which are equivalent), it is counted as true and the whole expression evaluates to the value of the <i>then</i> clause; otherwise it evaluates to the value of the optional <i>else</i> clause, if one is provided, or else to the empty list.
 
===Case===
<code>CASE</code> expressions resemble the multi-way branching constructs found in most programming languages: an expression is evaluated, and the value of the whole expression is provided by the first clause that evaluates to a true value. Optionally, an <code>ELSE</code> expression can be provided, in case none of the clauses fits.
<langsyntaxhighlight lang="lisp">(case s
("Rosetta Code" "Ah yes, the chrestomathy site")
("Stack Overflow" "Oh dear me, having problems are you?")
("Github" "Say no more")
(else "Sorry, never heard of it") )</langsyntaxhighlight>
 
===Cond===
<code>COND</code> is a more general conditional than <code>IF</code> or <code>CASE</code>: it resembles a <code>CASE</code> statement, but with the option of using a different conditional expression in each clause. A default value can be provided using <code>ELSE</code>, as with <code>CASE</code>, or any expression that is guaranteed to return a value other than <code>NIL</code> or the empty list.
<langsyntaxhighlight lang="lisp">(cond
((eq s "Rosetta Code") "Chrestomathy site")
((> n 37) "Some other appropriate value, presumably")
(t "If you're seeing me, s wasn't equal to Rosetta Code and n must have been 37 or below") )</langsyntaxhighlight>
 
=={{header|XPL0}}==
Line 7,903 ⟶ 8,777:
=={{header|XSLT}}==
The <xsl:if> element allows simple conditional processing.
<langsyntaxhighlight lang="xml"><xsl:if test="condition">
<!-- executed if XPath expression evaluates to true -->
</xsl:if></langsyntaxhighlight>
The <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements allow more general conditional processing.
<langsyntaxhighlight lang="xml"><xsl:choose>
<xsl:when test="condition1">
<!-- included if condition1 evaluates to true (like C `if`) -->
Line 7,923 ⟶ 8,797:
<!-- (The `otherwise` element is optional) -->
</xsl:otherwise>
</xsl:choose></langsyntaxhighlight>
 
The XPath expressions in the <code>test</code> attribute are evaluated in boolean context (converted as if by [http://www.w3.org/TR/xpath/#function-boolean the boolean function] if necessary).
 
<langsyntaxhighlight lang="xml"><xsl:if test="@attrib = 'foo'">...</xsl:if>
<xsl:if test="position() != last()">...</xsl:if>
<xsl:if test="not(false())">...</xsl:if>
Line 7,937 ⟶ 8,811:
implicitly converted to boolean. -->
<xsl:if test="boolean($expr)">...</xsl:if>
<xsl:if test="$expr">...</xsl:if></langsyntaxhighlight>
 
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
<lang Yabasic>
// if-then-endif, switch / end switch
// on gosub, on goto
Line 8,007 ⟶ 8,881:
sentencia(s)
end while
</syntaxhighlight>
</lang>
 
 
Line 8,018 ⟶ 8,892:
We'll look at this example in C and in Z80 Assembly:
 
<syntaxhighlight lang="c">
<lang C>
char x;
if (x == 20)
Line 8,027 ⟶ 8,901:
{
doThat();
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="z80">cp 20
jr nz,Else
call doThis
Line 8,036 ⟶ 8,910:
Else:
call doThat
done</langsyntaxhighlight>
 
While the Z80 does support conditional calls and returns, in this example they weren't a good choice, since there's no guarantee that the function <code>doThis</code> won't alter the flags, and you can't back up/restore the flags on the stack without backing up/restoring the accumulator at the same time, which isn't always what you want.
Line 8,043 ⟶ 8,917:
 
C code:
<langsyntaxhighlight Clang="c">if (x == 20)
{
DoSomething();
}
// rest of program</langsyntaxhighlight>
 
Z80 Assembly code:
<langsyntaxhighlight lang="z80">
cp 20
call z,DoSomething
;rest of program</langsyntaxhighlight>
 
If the accumulator didn't equal 20, no <code>CALL</code> will actually take place.
Line 8,059 ⟶ 8,933:
===Switch===
Switch cases can be implemented in a few ways. The simplest way is by checking each value individually.
<langsyntaxhighlight Z80lang="z80">ld a,(HL) ;switch (HL)
cp 1 ;case (1)
jr nz,+ ;branch to next colon (note: not all assemblers support this syntax)
Line 8,072 ⟶ 8,946:
call HL_EQUALS_50
:
;rest of program</langsyntaxhighlight>
 
The above example continues to check the other cases even after a match is found. If you don't want that to happen, do this:
<langsyntaxhighlight lang="z80">ld a,(HL) ;switch (HL)
cp 1 ;case (1)
jr nz,+ ;branch to next lone colon
Line 8,091 ⟶ 8,965:
:
done:
;rest of program</langsyntaxhighlight>
 
Another way to implement switch cases is with a lookup table of functions. This uses a command called <code>JP (HL)</code>. Despite the parentheses around <code>(HL)</code>, no dereferencing takes place - the program counter is simply set to the value in <code>HL</code>. This method is a little more complicated but allows you to create an indexed array of functions and choose one to execute. This method doesn't allow for fallthrough. You have to create a dispatcher that you can CALL, and pre-load the accumulator with the desired index and HL with the pointer to the 0th function in the table. Wherever you go needs to end in a <code>RET</code> instruction, so that you'll end up just after you <code>CALL</code>ed the dispatcher.
 
<langsyntaxhighlight lang="z80">Dispatch: ;remember, you need to CALL this address for it to work properly. Otherwise your program will most likely crash.
add a ;this is a table of 16-bit values, so multiply the index by 2.
ld a,(hl) ;get the low byte of the function addr. you wish to call
Line 8,104 ⟶ 8,978:
pop af
ld L,a ;store the low byte in L
jp (HL) ;now you've jumped to the desired function. Its RET will return execution to the instruction just after "CALL Dispatch"</langsyntaxhighlight>
 
The disadvantage to this method is that it relies on the case values being consecutive. If they're not, you're better off using the other method, but you can still implement this if you pad the lookup table with pointers to a <code>RET</code>, which will make you return immediately back to after the dispatch call, without having done anything.
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">if (x) y else z;
if(a)b else if (c) else d; etc
x:=(if (a) b else c);
Line 8,121 ⟶ 8,995:
case(b){...}
else {...} // case a C's default, has to be at the end
}</langsyntaxhighlight>
 
=={{header|Zig}}==
<langsyntaxhighlight lang="zig">const std = @import("std");
const builtin = @import("builtin");
 
Line 8,186 ⟶ 9,060:
 
// TODO Arithmetic if once https://github.com/ziglang/zig/issues/8220 is finished
}</langsyntaxhighlight>
 
{{omit from|GUISS}}
5

edits