Conditional structures: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 16: Line 16:
=={{header|11l}}==
=={{header|11l}}==
===if-else===
===if-else===
<lang 11l>I x == 0
<syntaxhighlight lang="11l">I x == 0
foo()
foo()
E I x == 1
E I x == 1
bar()
bar()
E
E
baz()</lang>
baz()</syntaxhighlight>


===switch===
===switch===
<lang 11l>S x
<syntaxhighlight lang="11l">S x
0
0
foo()
foo()
Line 30: Line 30:
bar()
bar()
E
E
baz()</lang>
baz()</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
Here are the branch mnemonic opcodes:
Here are the branch mnemonic opcodes:
<lang 360asm>* Unconditional Branch or No Branch:
<syntaxhighlight lang="360asm">* Unconditional Branch or No Branch:
B label Unconditional
B label Unconditional
BR Rx "
BR Rx "
Line 81: Line 81:
BNMR Rx "
BNMR Rx "
BNZ label Branch if Not Zero
BNZ label Branch if Not Zero
BNZR Rx "</lang>
BNZR Rx "</syntaxhighlight>
The ASM (Assembler Structured Macros) toolkit brings structures to IBM assembler 360.
The ASM (Assembler Structured Macros) toolkit brings structures to IBM assembler 360.
<lang 360asm> expression:
<syntaxhighlight lang="360asm"> expression:
opcode,op1,rel,op2
opcode,op1,rel,op2
opcode,op1,rel,op2,OR,opcode,op1,rel,op2
opcode,op1,rel,op2,OR,opcode,op1,rel,op2
Line 155: Line 155:
CASE 7 case 7
CASE 7 case 7
LA R5,4 r5=4
LA R5,4 r5=4
ENDCASE end select</lang>
ENDCASE end select</syntaxhighlight>


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
Line 161: Line 161:
6502 Assembly has 8 conditional branch instructions; each instruction will test the appropriate flag and condition and jump between -128 and 127 bytes.
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:
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:
<lang 6502asm> LDA #10
<syntaxhighlight lang="6502asm"> LDA #10
CMP #11</lang>
CMP #11</syntaxhighlight>
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.
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.
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.
<lang 6502asm> BNE ;Branch on Not Equal - branch when the zero flag is set
<syntaxhighlight 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.
BEQ ;Branch on EQual - branch when the zero flag is set.
;The zero flag is set when the result of an operation is zero
;The zero flag is set when the result of an operation is zero
Line 184: Line 184:
;a subtraction produced a borrow and cleared if an addition/subtraction
;a subtraction produced a borrow and cleared if an addition/subtraction
;does not produce a carry/borrow. The carry flag also holds bits
;does not produce a carry/borrow. The carry flag also holds bits
;after shifts and rotates.</lang>
;after shifts and rotates.</syntaxhighlight>
In the following example, the branch will be taken if memory location Variable holds 200:
In the following example, the branch will be taken if memory location Variable holds 200:
<lang 6502asm> LDA #200
<syntaxhighlight lang="6502asm"> LDA #200
CMP Variable
CMP Variable
BEQ #3 ;if equal, skip ahead 3 bytes...
BEQ #3 ;if equal, skip ahead 3 bytes...
CLC ;if unequal, continue executing instructions
CLC ;if unequal, continue executing instructions
ADC #1
ADC #1
STA OtherVariable ; ...to here.</lang>
STA OtherVariable ; ...to here.</syntaxhighlight>
Because you don't have to perform a comparison to set the flags, you can perform very fast checks in iterative loops:
Because you don't have to perform a comparison to set the flags, you can perform very fast checks in iterative loops:
<lang 6502asm> LDX #100
<syntaxhighlight lang="6502asm"> LDX #100
Loop: ...do something
Loop: ...do something
DEX
DEX
BNE Loop</lang>
BNE Loop</syntaxhighlight>
This code will loop until X is zero.
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.
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: Line 203:
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.
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.


<lang 6502asm>ReturnTable:
<syntaxhighlight lang="6502asm">ReturnTable:
dw foo-1 ;each is a label to a section of code that ends in an RTS
dw foo-1 ;each is a label to a section of code that ends in an RTS
dw bar-1
dw bar-1
Line 223: Line 223:
; If done properly, return spoofing will not corrupt the stack.
; 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.</lang>
RTS ;this "RTS" acts as a JMP to the address we just put on the stack.</syntaxhighlight>
=={{header|68000 Assembly}}==
=={{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.
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: Line 231:
===CMP===
===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.
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.
<lang 68000devpac>MOVE.L #$FFFFFF00,D0
<syntaxhighlight lang="68000devpac">MOVE.L #$FFFFFF00,D0
CMP.B #0,D0 ;equals zero, so zero flag is set.
CMP.B #0,D0 ;equals zero, so zero flag is set.
CMP.W #0,D0 ;doesn't equals zero, so zero flag is clear.</lang>
CMP.W #0,D0 ;doesn't equals zero, so zero flag is clear.</syntaxhighlight>


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:
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: Line 249:
===Bit Testing===
===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).
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).
<lang 68000devpac>BTST #7,D0 ;test bit 7 of D0, i.e. the leftmost bit in the rightmost byte.
<syntaxhighlight 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"
BNE goHere ;if that bit is 1, branch to "goHere"
BEQ goThere ;if that bit is 0, branch to "goThere"</lang>
BEQ goThere ;if that bit is 0, branch to "goThere"</syntaxhighlight>


<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.
<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: Line 260:
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.
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.


<lang 68000devpac>CMP.L #3,D0 ;this works with any size operands, not just L.
<syntaxhighlight lang="68000devpac">CMP.L #3,D0 ;this works with any size operands, not just L.
BNE doNothing
BNE doNothing
ADD.L #7,D0
ADD.L #7,D0
doNothing:
doNothing:
;rest of program</lang>
;rest of program</syntaxhighlight>


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.
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: Line 272:
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.
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.


<lang 68000devpac>SwitchCase:
<syntaxhighlight 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.)
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)
; D0 is the case selector variable (byte-sized)
Line 305: Line 305:


default:
default:
rts</lang>
rts</syntaxhighlight>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program condstr64.s */
/* program condstr64.s */
Line 530: Line 530:
.include "../includeARM64.inc"
.include "../includeARM64.inc"


</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
INT i
INT i


Line 546: Line 546:
FI
FI
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Conditional_structures.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Conditional_structures.png Screenshot from Atari 8-bit computer]
Line 560: Line 560:
=={{header|Ada}}==
=={{header|Ada}}==
===if-then-else===
===if-then-else===
<lang ada>type Restricted is range 1..10;
<syntaxhighlight lang="ada">type Restricted is range 1..10;
My_Var : Restricted;
My_Var : Restricted;


Line 569: Line 569:
else
else
-- do something
-- do something
end if;</lang>
end if;</syntaxhighlight>
===conditional expressions===
===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.
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====
====if expression====
<lang ada>type Operation is (Add, Subtract, Multiply, Divide);
<syntaxhighlight lang="ada">type Operation is (Add, Subtract, Multiply, Divide);
Op : Operation;
Op : Operation;
Result : Integer;
Result : Integer;
Line 585: Line 585:
elsif Op = Divide then
elsif Op = Divide then
A / B
A / B
);</lang>
);</syntaxhighlight>
====case expressions====
====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:
Using the same example above, we assume that the <syntaxhighlight lang="ada">Operation</syntaxhighlight>, <syntaxhighlight lang="ada">Op</syntaxhighlight>, and <syntaxhighlight lang="ada">Result</syntaxhighlight> variables are declared. A case expression over the enumeration of operations might look like:
<lang ada>Result := (case Op is
<syntaxhighlight lang="ada">Result := (case Op is
Add => A + B,
Add => A + B,
Subtract => A - B,
Subtract => A - B,
Line 594: Line 594:
Divide => A / B
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 (<lang ada>case Op of...</lang>). 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.
Note: some websites (particularly [https://www.radford.edu/nokie/classes/320/abe/operators.html#:~:text=if%20and%20case-,Examples%3A,1%2C%20others%20%3D%3E%200)%3B this one]) contain a different variant of a case expression (<syntaxhighlight lang="ada">case Op of...</syntaxhighlight>). The Ada Reference Manual indicates this is incorrect, and we use the [http://www.ada-auth.org/standards/12rm/html/RM-4-5-7.html formal version] here.
===case with a default alternative===
===case with a default alternative===
<lang ada>type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
<syntaxhighlight lang="ada">type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
Today : Days;
Today : Days;


Line 609: Line 609:
when others =>
when others =>
Accumulate_Sales;
Accumulate_Sales;
end case;</lang>
end case;</syntaxhighlight>


===case without a default===
===case without a default===
Line 615: Line 615:
I.e., the following code is syntactically incorrect:
I.e., the following code is syntactically incorrect:


<lang ada>case Today is
<syntaxhighlight lang="ada">case Today is
when Monday =>
when Monday =>
Compute_Starting_Balance;
Compute_Starting_Balance;
Line 623: Line 623:
Accumulate_Sales;
Accumulate_Sales;
-- ignore Saturday and Sunday
-- ignore Saturday and Sunday
end case;</lang>
end case;</syntaxhighlight>


The syntactically correct version:
The syntactically correct version:


<lang ada>case Today is
<syntaxhighlight lang="ada">case Today is
when Saturday | Sunday =>
when Saturday | Sunday =>
null; -- don't do anything, if Today is Saturday or Sunday
null; -- don't do anything, if Today is Saturday or Sunday
Line 636: Line 636:
when Tuesday .. Thursday =>
when Tuesday .. Thursday =>
Accumulate_Sales;
Accumulate_Sales;
end case;</lang>
end case;</syntaxhighlight>


===select===
===select===
Line 643: Line 643:


====Conditional Accept====
====Conditional Accept====
<lang ada>select
<syntaxhighlight lang="ada">select
accept first_entry;
accept first_entry;
-- do something
-- do something
Line 649: Line 649:
-- do something
-- do something
or terminate;
or terminate;
end select;</lang>
end select;</syntaxhighlight>


====Conditional entry call====
====Conditional entry call====
A selective entry call provides a way to time-out an 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.
Without the time-out the calling task will suspend until the entry call is accepted.
<lang ada>select
<syntaxhighlight lang="ada">select
My_Task.Start;
My_Task.Start;
or
or
delay Timeout_Period;
delay Timeout_Period;
end select;</lang>
end select;</syntaxhighlight>
The entry Start on the task My_Task will be called.
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.
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: Line 664:
=={{header|Aikido}}==
=={{header|Aikido}}==
===Conditional Expressions===
===Conditional Expressions===
<lang aikido>
<syntaxhighlight lang="aikido">
var x = loggedin ? sessionid : -1
var x = loggedin ? sessionid : -1


</syntaxhighlight>
</lang>


===if..elif..else===
===if..elif..else===
<lang aikido>
<syntaxhighlight lang="aikido">
if (value > 40) {
if (value > 40) {
println ("OK")
println ("OK")
Line 678: Line 678:
println ("RETRY")
println ("RETRY")
}
}
</syntaxhighlight>
</lang>


===switch===
===switch===
<lang aikido>
<syntaxhighlight lang="aikido">
switch (arg) {
switch (arg) {
case "-d":
case "-d":
Line 707: Line 707:
println ("RETRY")
println ("RETRY")
}
}
</syntaxhighlight>
</lang>


=={{header|Aime}}==
=={{header|Aime}}==
Line 713: Line 713:
===If-elif-else===
===If-elif-else===


<lang aime>if (c1) {
<syntaxhighlight lang="aime">if (c1) {
// first condition is true...
// first condition is true...
} elif (c2) {
} elif (c2) {
Line 721: Line 721:
} else {
} else {
// none was true...
// none was true...
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 60}}==
=={{header|ALGOL 60}}==
Line 734: Line 734:
'''if''' X=Y '''then''' K:=I
'''if''' X=Y '''then''' K:=I
An example:
An example:
<lang algol60> 'IF' I=1 'THEN' OUTINTEGER(1,I);
<syntaxhighlight lang="algol60"> 'IF' I=1 'THEN' OUTINTEGER(1,I);


'IF' I<J 'THEN' OUTSTRING(1,'(' : I<J')')
'IF' I<J 'THEN' OUTSTRING(1,'(' : I<J')')
Line 746: Line 746:
OUTSTRING(1,'(' J=')');
OUTSTRING(1,'(' J=')');
OUTINTEGER(1,J)
OUTINTEGER(1,J)
'END'</lang>
'END'</syntaxhighlight>
Algol 60 has also a switch structure:
Algol 60 has also a switch structure:
declaration::= '''switch''' switch:=list_of labels
declaration::= '''switch''' switch:=list_of labels
statement::= '''goto''' switch[expression]
statement::= '''goto''' switch[expression]
An example:
An example:
<lang algol60> 'SWITCH' TARGET:=L1,L2,L3;
<syntaxhighlight lang="algol60"> 'SWITCH' TARGET:=L1,L2,L3;
...
...
'GOTO' TARGET(/J/);
'GOTO' TARGET(/J/);
L1: OUTSTRING(1,'('AA')');
L1: OUTSTRING(1,'('AA')');
L2: OUTSTRING(1,'('BB')');
L2: OUTSTRING(1,'('BB')');
L3: OUTSTRING(1,'('CC')');</lang>
L3: OUTSTRING(1,'('CC')');</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 762: Line 762:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
integer a, b, c;
integer a, b, c;


Line 793: Line 793:
write( case c - a of ( "one", "two", "three", "four" ) )
write( case c - a of ( "one", "two", "three", "four" ) )


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 810: Line 810:
The second and third arguments should be blocks (aka anonymous functions or thunks).
The second and third arguments should be blocks (aka anonymous functions or thunks).


<lang ambienttalk>
<syntaxhighlight lang="ambienttalk">
if: condition then: {
if: condition then: {
// condition is true...
// condition is true...
Line 816: Line 816:
// condition is false...
// condition is false...
}
}
</syntaxhighlight>
</lang>


===IfTrue/IfFalse===
===IfTrue/IfFalse===
Line 822: Line 822:
One can also send a message to the boolean objects true and false:
One can also send a message to the boolean objects true and false:


<lang ambienttalk>
<syntaxhighlight lang="ambienttalk">
condition.ifTrue: { /* condition is true... */ } ifFalse: { /* condition is false... */ }
condition.ifTrue: { /* condition is true... */ } ifFalse: { /* condition is false... */ }
</syntaxhighlight>
</lang>


=={{header|AmigaE}}==
=={{header|AmigaE}}==
'''IF-THEN-ELSE'''
'''IF-THEN-ELSE'''
<lang amigae>IF condition
<syntaxhighlight lang="amigae">IF condition
-> if condition is true...
-> if condition is true...
ELSEIF condition2
ELSEIF condition2
Line 834: Line 834:
ELSE
ELSE
-> if all other conditions are not true...
-> if all other conditions are not true...
ENDIF</lang>
ENDIF</syntaxhighlight>


or on one single line:
or on one single line:


<lang amigae>IF condition THEN statement</lang>
<syntaxhighlight lang="amigae">IF condition THEN statement</syntaxhighlight>


'''Ternary IF THEN ELSE'''
'''Ternary IF THEN ELSE'''


The IF-THEN-ELSE can be used like ternary operator (?: in C)
The IF-THEN-ELSE can be used like ternary operator (?: in C)
<lang amigae>DEF c
<syntaxhighlight lang="amigae">DEF c
c := IF condition THEN 78 ELSE 19</lang>
c := IF condition THEN 78 ELSE 19</syntaxhighlight>


'''SELECT-CASE'''
'''SELECT-CASE'''


<lang amigae>SELECT var
<syntaxhighlight lang="amigae">SELECT var
CASE n1
CASE n1
-> code
-> code
Line 855: Line 855:
DEFAULT
DEFAULT
-> no one of the previous case...
-> no one of the previous case...
ENDSELECT</lang>
ENDSELECT</syntaxhighlight>


Another version allows for ranges:
Another version allows for ranges:


<lang amigae>SELECT max_possible_value OF var
<syntaxhighlight lang="amigae">SELECT max_possible_value OF var
CASE n1
CASE n1
-> code
-> code
Line 868: Line 868:
DEFAULT
DEFAULT
-> none of previous ones
-> none of previous ones
ENDSELECT</lang>
ENDSELECT</syntaxhighlight>


The biggest among n1, n2 and so on, must be not bigger than max_possible_value.
The biggest among n1, n2 and so on, must be not bigger than max_possible_value.
Line 874: Line 874:
=={{header|Apex}}==
=={{header|Apex}}==
===if-then-else===
===if-then-else===
<lang java>if (s == 'Hello World') {
<syntaxhighlight lang="java">if (s == 'Hello World') {
foo();
foo();
} else if (s == 'Bye World') {
} else if (s == 'Bye World') {
Line 880: Line 880:
} else {
} else {
deusEx();
deusEx();
}</lang>
}</syntaxhighlight>
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
<lang java>if(obj != null && obj.foo()){
<syntaxhighlight lang="java">if(obj != null && obj.foo()){
aMethod();
aMethod();
}</lang>
}</syntaxhighlight>
<tt>obj.foo()</tt> will not be executed if <tt>obj != null</tt> returns false. It is possible to have conditionals without short circuit evaluation using the <tt>&</tt> and <tt>|</tt> operators (from [[Bitwise operations]]). So in this conditional:
<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:
<lang java>if(obj != null & obj.foo()){
<syntaxhighlight lang="java">if(obj != null & obj.foo()){
aMethod();
aMethod();
}</lang>
}</syntaxhighlight>
You will get a null pointer exception if obj is null.
You will get a null pointer exception if obj is null.
===ternary===
===ternary===


<lang java>s == 'Hello World' ? foo() : bar();</lang>
<syntaxhighlight lang="java">s == 'Hello World' ? foo() : bar();</syntaxhighlight>


===switch===
===switch===
Line 899: Line 899:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
===if-then-else===
===if-then-else===
<lang applescript>if myVar is "ok" then return true
<syntaxhighlight lang="applescript">if myVar is "ok" then return true


set i to 0
set i to 0
Line 908: Line 908:
else
else
return "odd"
return "odd"
end if</lang>
end if</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 1,063: Line 1,063:
bx lr /* return */
bx lr /* return */


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
===if?-else===
===if?-else===


<lang rebol>num: 2
<syntaxhighlight lang="rebol">num: 2


if? num=2 [
if? num=2 [
Line 1,075: Line 1,075:
else [
else [
print "something went wrong..."
print "something went wrong..."
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 1,083: Line 1,083:
===case-when?===
===case-when?===


<lang rebol>loop 1..5 'num [
<syntaxhighlight lang="rebol">loop 1..5 'num [
case [num]
case [num]
when? [<2] -> print [num ": it's less than 2"]
when? [<2] -> print [num ": it's less than 2"]
Line 1,090: Line 1,090:
else -> print [num ": the number is too big"]
else -> print [num ": the number is too big"]
]
]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,101: Line 1,101:


=={{header|Astro}}==
=={{header|Astro}}==
<lang python>if x == 0:
<syntaxhighlight lang="python">if x == 0:
foo()
foo()
elif x == 1:
elif x == 1:
Line 1,116: Line 1,116:
_ => qux()
_ => qux()


(a) ? b : c</lang>
(a) ? b : c</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==


===if, else if, else===
===if, else if, else===
<syntaxhighlight lang="autohotkey">x = 1
<lang AutoHotkey>x = 1
If x
If x
MsgBox, x is %x%
MsgBox, x is %x%
Line 1,127: Line 1,127:
MsgBox, x is %x%
MsgBox, x is %x%
Else
Else
MsgBox, x is %x%</lang>
MsgBox, x is %x%</syntaxhighlight>


===ternary if===
===ternary if===
<syntaxhighlight lang="autohotkey">x = 2
<lang AutoHotkey>x = 2
y = 1
y = 1
var := x > y ? 2 : 3
var := x > y ? 2 : 3
MsgBox, % var</lang>
MsgBox, % var</syntaxhighlight>


===while (looping if)===
===while (looping if)===
<lang AutoHotkey>While (A_Index < 3) {
<syntaxhighlight lang="autohotkey">While (A_Index < 3) {
MsgBox, %A_Index% is less than 3
MsgBox, %A_Index% is less than 3
}</lang>
}</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
===If, ElseIf, Else===
===If, ElseIf, Else===
<lang AutoIt>If <expression> Then
<syntaxhighlight lang="autoit">If <expression> Then
statements
statements
...
...
Line 1,152: Line 1,152:
...
...
EndIf
EndIf
</syntaxhighlight>
</lang>
===Select Case===
===Select Case===
<lang AutoIt>Select
<syntaxhighlight lang="autoit">Select
Case <expression>
Case <expression>
statement1
statement1
Line 1,165: Line 1,165:
...]
...]
EndSelect
EndSelect
</syntaxhighlight>
</lang>
===Switch Case===
===Switch Case===
<lang AutoIt>Switch <expression>
<syntaxhighlight lang="autoit">Switch <expression>
Case <value> [To <value>] [,<value> [To <value>] ...]
Case <value> [To <value>] [,<value> [To <value>] ...]
statement1
statement1
Line 1,178: Line 1,178:
...]
...]
EndSwitch
EndSwitch
</syntaxhighlight>
</lang>
--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 15:39, 13 November 2013 (UTC)
--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 15:39, 13 November 2013 (UTC)


=={{header|Avail}}==
=={{header|Avail}}==
===If-Then-Else===
===If-Then-Else===
<lang Avail>If year = 1999 then [Print: "Party!";];
<syntaxhighlight lang="avail">If year = 1999 then [Print: "Party!";];


If someNumber > 5 then [Print: "Too high!";] else [Print: "Adequate amount.";];
If someNumber > 5 then [Print: "Too high!";] else [Print: "Adequate amount.";];
Line 1,191: Line 1,191:
else [score := 45;];
else [score := 45;];


Unless char = ¢X then [Print: "character was not an x";];</lang>
Unless char = ¢X then [Print: "character was not an x";];</syntaxhighlight>


===Ternary===
===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.
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.
<lang Avail>Print: if result = 13 then ["unlucky"] else ["safe"];</lang>
<syntaxhighlight lang="avail">Print: if result = 13 then ["unlucky"] else ["safe"];</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Conditionals in awk are modelled after C:
Conditionals in awk are modelled after C:
<lang awk>if(i<0) i=0; else i=42</lang>
<syntaxhighlight lang="awk">if(i<0) i=0; else i=42</syntaxhighlight>
For a branch with more than a single statement, this needs braces:
For a branch with more than a single statement, this needs braces:
<lang awk>
<syntaxhighlight lang="awk">
if(i<0) {
if(i<0) {
i=0; j=1
i=0; j=1
} else {
} else {
i=42; j=2
i=42; j=2
}</lang>
}</syntaxhighlight>
There is also the ternary conditional:
There is also the ternary conditional:
<lang awk>i=(i<0? 0: 42)</lang>
<syntaxhighlight lang="awk">i=(i<0? 0: 42)</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
Line 1,215: Line 1,215:


===Simple===
===Simple===
<lang axe>If 1
<syntaxhighlight lang="axe">If 1
YEP()
YEP()
End</lang>
End</syntaxhighlight>


===Inverse If===
===Inverse If===
<lang axe>!If 1
<syntaxhighlight lang="axe">!If 1
NOPE()
NOPE()
End</lang>
End</syntaxhighlight>


===If-Else===
===If-Else===
<lang axe>If 1
<syntaxhighlight lang="axe">If 1
YEP()
YEP()
Else
Else
NOPE()
NOPE()
End</lang>
End</syntaxhighlight>


Axe has no support for switch-like statements. If-ElseIf-Else structures are required to achieve the same goal.
Axe has no support for switch-like statements. If-ElseIf-Else structures are required to achieve the same goal.


===If-ElseIf-Else===
===If-ElseIf-Else===
<lang axe>If 1=0
<syntaxhighlight lang="axe">If 1=0
NOPE()
NOPE()
ElseIf 1=1
ElseIf 1=1
Line 1,240: Line 1,240:
Else
Else
NOPE()
NOPE()
End</lang>
End</syntaxhighlight>


===If-InverseElseIf-Else===
===If-InverseElseIf-Else===
<lang axe>If 1=0
<syntaxhighlight lang="axe">If 1=0
NOPE()
NOPE()
Else!If 1=2
Else!If 1=2
Line 1,249: Line 1,249:
Else
Else
NOPE()
NOPE()
End</lang>
End</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
Line 1,255: Line 1,255:
===Simple select===
===Simple select===


<lang babel>
<syntaxhighlight lang="babel">
"foo" "bar" 3 4 > sel <<
"foo" "bar" 3 4 > sel <<
</syntaxhighlight>
</lang>


Prints "foo" since '3 4 >' evaluates to false, which causes sel to remove "bar" from the stack.
Prints "foo" since '3 4 >' evaluates to false, which causes sel to remove "bar" from the stack.
Line 1,263: Line 1,263:
===If-Then-Else===
===If-Then-Else===


<lang babel>
<syntaxhighlight lang="babel">
{3 4 >}
{3 4 >}
{"foo"}
{"foo"}
Line 1,269: Line 1,269:
ifte
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.
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: Line 1,275:
===Conditional===
===Conditional===


<lang babel>
<syntaxhighlight lang="babel">
({3 4 >} {"Three is greater than four" }
({3 4 >} {"Three is greater than four" }
{3 3 >} {"Three is greater than three"}
{3 3 >} {"Three is greater than three"}
Line 1,282: Line 1,282:
cond
cond
<<
<<
</syntaxhighlight>
</lang>


Prints "Three is greater than two", as expected.
Prints "Three is greater than two", as expected.
Line 1,292: Line 1,292:
BASIC can use the if statement to perform conditional operations:
BASIC can use the if statement to perform conditional operations:


<lang basic>10 LET A%=1: REM A HAS A VALUE OF TRUE
<syntaxhighlight lang="basic">10 LET A%=1: REM A HAS A VALUE OF TRUE
20 IF A% THEN PRINT "A IS TRUE"
20 IF A% THEN PRINT "A IS TRUE"
30 WE CAN OF COURSE USE EXPRESSIONS
30 WE CAN OF COURSE USE EXPRESSIONS
Line 1,298: Line 1,298:
50 IF NOT(A%) THEN PRINT "A IS FALSE"
50 IF NOT(A%) THEN PRINT "A IS FALSE"
60 REM SOME VERSIONS OF BASIC PROVIDE AN ELSE KEYWORD
60 REM SOME VERSIONS OF BASIC PROVIDE AN ELSE KEYWORD
70 IF A% THEN PRINT "A IS TRUE" ELSE PRINT "A IS FALSE"</lang>
70 IF A% THEN PRINT "A IS TRUE" ELSE PRINT "A IS FALSE"</syntaxhighlight>


Here are code snippets from a more modern variant that does not need line numbers:
Here are code snippets from a more modern variant that does not need line numbers:
Line 1,306: Line 1,306:
Single line IF does not require END IF
Single line IF does not require END IF


<lang qbasic>IF x = 0 THEN doSomething
<syntaxhighlight lang="qbasic">IF x = 0 THEN doSomething
IF x < 0 THEN doSomething ELSE doOtherThing</lang>
IF x < 0 THEN doSomething ELSE doOtherThing</syntaxhighlight>


Multi-line IF:
Multi-line IF:


<lang qbasic>IF x > 0 AND x < 10 THEN
<syntaxhighlight lang="qbasic">IF x > 0 AND x < 10 THEN
'do stuff
'do stuff
ELSE IF x = 0 THEN
ELSE IF x = 0 THEN
Line 1,317: Line 1,317:
ELSE
ELSE
'do more stuff
'do more stuff
END IF</lang>
END IF</syntaxhighlight>


Like in [[#C|C]], any non-zero value is interpreted as True:
Like in [[#C|C]], any non-zero value is interpreted as True:


<lang qbasic>IF aNumber THEN
<syntaxhighlight lang="qbasic">IF aNumber THEN
'the number is not 0
'the number is not 0
ELSE
ELSE
'the number is 0
'the number is 0
END IF</lang>
END IF</syntaxhighlight>


===select case===
===select case===
Line 1,332: Line 1,332:
The condition in each case branch can be one or more constants or variables, a range or an expression.
The condition in each case branch can be one or more constants or variables, a range or an expression.


<lang qbasic>SELECT CASE expression
<syntaxhighlight lang="qbasic">SELECT CASE expression
CASE 1
CASE 1
'do stuff
'do stuff
Line 1,343: Line 1,343:
CASE ELSE
CASE ELSE
'default case
'default case
END SELECT</lang>
END SELECT</syntaxhighlight>


===Computed ON-GOTO===
===Computed ON-GOTO===
Line 1,351: Line 1,351:
or:
or:


<lang basic>10 INPUT "Enter 1,2 or 3: ";v
<syntaxhighlight lang="basic">10 INPUT "Enter 1,2 or 3: ";v
20 GOTO v * 100
20 GOTO v * 100
99 STOP
99 STOP
Line 1,359: Line 1,359:
210 STOP
210 STOP
300 PRINT "Cherry"
300 PRINT "Cherry"
310 STOP</lang>
310 STOP</syntaxhighlight>


===Conditional loops===
===Conditional loops===
Line 1,365: Line 1,365:
Some variants of basic support conditional loops:
Some variants of basic support conditional loops:


<lang bbcbasic>10 REM while loop
<syntaxhighlight lang="bbcbasic">10 REM while loop
20 L=0
20 L=0
30 WHILE L<5
30 WHILE L<5
Line 1,376: Line 1,376:
100 PRINT L
100 PRINT L
110 L=L+1
110 L=L+1
120 UNTIL L>5</lang>
120 UNTIL L>5</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
Applesoft BASIC does not have ELSE, only the IF-THEN structure and computed ON-GOSUB and ON-GOTO
Applesoft BASIC does not have ELSE, only the IF-THEN structure and computed ON-GOSUB and ON-GOTO
<lang ApplesoftBasic> 10 LET X = 1
<syntaxhighlight lang="applesoftbasic"> 10 LET X = 1
20 IF X THEN PRINT "X IS TRUE"
20 IF X THEN PRINT "X IS TRUE"
30 IF NOT X THEN PRINT "X IS FALSE"
30 IF NOT X THEN PRINT "X IS FALSE"
Line 1,387: Line 1,387:
100 PRINT "APPLE": RETURN
100 PRINT "APPLE": RETURN
200 PRINT "BANANA": RETURN
200 PRINT "BANANA": RETURN
300 PRINT "CHERRY"</lang>
300 PRINT "CHERRY"</syntaxhighlight>


=={{header|BASIC256}}==
=={{header|BASIC256}}==
Line 1,429: Line 1,429:
</pre>
</pre>
I think this test shows that nested if statements parse as they do in c.
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 i = 0 to 1
for j = 0 to 1
for j = 0 to 1
Line 1,449: Line 1,449:
next j
next j
next i
next i
</syntaxhighlight>
</lang>


=={{header|Batch File}}==
=={{header|Batch File}}==
IF syntax:
IF syntax:
<lang dos>
<syntaxhighlight lang="dos">
IF [NOT] ERRORLEVEL number command
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] string1==string2 command
Line 1,468: Line 1,468:
GEQ - greater than or equal
GEQ - greater than or equal
/I case insensitive string compares
/I case insensitive string compares
</syntaxhighlight>
</lang>
The ELSE clause must be on the same line as the command after the IF.
The ELSE clause must be on the same line as the command after the IF.
For example:
For example:
<lang dos>
<syntaxhighlight lang="dos">
IF EXIST %filename% (
IF EXIST %filename% (
del %filename%
del %filename%
Line 1,477: Line 1,477:
echo %filename% not found
echo %filename% not found
)
)
</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> REM Single-line IF ... THEN ... ELSE (ELSE clause is optional):
<syntaxhighlight lang="bbcbasic"> REM Single-line IF ... THEN ... ELSE (ELSE clause is optional):
IF condition% THEN statements ELSE statements
IF condition% THEN statements ELSE statements


Line 1,505: Line 1,505:


REM ON ... PROC (ELSE clause is optional):
REM ON ... PROC (ELSE clause is optional):
ON expression% PROCone, PROCtwo ... ELSE statements</lang>
ON expression% PROCone, PROCtwo ... ELSE statements</syntaxhighlight>


=={{header|beeswax}}==
=={{header|beeswax}}==
Line 1,512: Line 1,512:


The 4 conditional operators are:
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.
" 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.
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.</lang>
L lstack top value > 2nd value ? skip next instruction : don’t skip next instruction.</syntaxhighlight>


Example:
Example:
<lang Beeswax>_`Enter integer n:`T'p`n = 0`>N`Enter integer m:`T'p`m = 0`>` and `Kp`m = n`;
<syntaxhighlight lang="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`;
>`n > 0`d >`m > 0`d >Lp`m > n`;
>`m < n`;</lang>
>`m < n`;</syntaxhighlight>


Example output:
Example output:
<lang Beeswax>Enter integer n:
<syntaxhighlight lang="beeswax">Enter integer n:
i3
i3
n > 0
n > 0
Enter integer m:
Enter integer m:
i0
i0
m = 0 and m < n</lang>
m = 0 and m < n</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
Line 1,536: Line 1,536:
These snippets input a number and use the conditional operators to print a "0" if it is zero and an "X" otherwise.
These snippets input a number and use the conditional operators to print a "0" if it is zero and an "X" otherwise.


<lang befunge>v > "X",@ non-zero
<syntaxhighlight lang="befunge">v > "X",@ non-zero
> & |
> & |
> "0",@ zero</lang>
> "0",@ zero</syntaxhighlight>


'''#''' is the skip command.
'''#''' is the skip command.
It unconditionally skips one character, allowing a little flexibility in flow control.
It unconditionally skips one character, allowing a little flexibility in flow control.


<lang befunge>& #v_ "0",@ zero
<syntaxhighlight lang="befunge">& #v_ "0",@ zero
> "X",@ non-zero</lang>
> "X",@ non-zero</syntaxhighlight>


=={{header|blz}}==
=={{header|blz}}==
===if-else===
===if-else===
<lang blz>
<syntaxhighlight lang="blz">
if i % 2 == 0
if i % 2 == 0
print("even")
print("even")
Line 1,554: Line 1,554:
print("odd")
print("odd")
end
end
</syntaxhighlight>
</lang>


=={{header|Bori}}==
=={{header|Bori}}==
===if-elif-else===
===if-elif-else===
<lang bori>
<syntaxhighlight lang="bori">
if (i == 0)
if (i == 0)
return "zero";
return "zero";
Line 1,565: Line 1,565:
else
else
return "even";
return "even";
</syntaxhighlight>
</lang>


=={{header|BQN}}==
=={{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:
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:
<lang bqn>If ← {𝕏⍟𝕎@}´ # Also Repeat
<syntaxhighlight lang="bqn">If ← {𝕏⍟𝕎@}´ # Also Repeat
IfElse ← {c‿T‿F: c◶F‿T@}
IfElse ← {c‿T‿F: c◶F‿T@}
While ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´ # While 1‿{... to run forever
While ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´ # While 1‿{... to run forever
Line 1,579: Line 1,579:
Select ← {(⊑𝕩)◶(1↓𝕩)@}
Select ← {(⊑𝕩)◶(1↓𝕩)@}
Switch ← {c←⊑𝕩 ⋄ m‿a←<˘⍉∘‿2⥊1↓𝕩 ⋄ (⊑a⊐C)◶m@}
Switch ← {c←⊑𝕩 ⋄ m‿a←<˘⍉∘‿2⥊1↓𝕩 ⋄ (⊑a⊐C)◶m@}
Test ← {fn←{C‿A𝕊e:C◶A‿E}´𝕩⋄Fn@}</lang>
Test ← {fn←{C‿A𝕊e:C◶A‿E}´𝕩⋄Fn@}</syntaxhighlight>


The other method of branching is using function predicates, which can be used in any blocks for an if-else like conditional:
The other method of branching is using function predicates, which can be used in any blocks for an if-else like conditional:
<lang bqn>{
<syntaxhighlight lang="bqn">{
a<b ? a+↩1 ; # If
a<b ? a+↩1 ; # If
a<c ? c-↩1 ; # Else If
a<c ? c-↩1 ; # Else If
a-↩2 # Else
a-↩2 # Else
}</lang>
}</syntaxhighlight>


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.
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,602: Line 1,602:
The following expression writes "That's what I thought." to your screen and evaluates to the expression "Right".
The following expression writes "That's what I thought." to your screen and evaluates to the expression "Right".


<lang bracmat> 2+2:5
<syntaxhighlight lang="bracmat"> 2+2:5
& put$"Strange, must check that Bracmat interpreter."
& put$"Strange, must check that Bracmat interpreter."
& 0
& 0
| put$"That's what I thought."
| put$"That's what I thought."
& Right</lang>
& Right</syntaxhighlight>


=== switch-like branching ===
=== switch-like branching ===
Line 1,612: Line 1,612:
In the following example, the resulting expression is a single node containing "4".
In the following example, the resulting expression is a single node containing "4".


<lang bracmat> 2+2
<syntaxhighlight lang="bracmat"> 2+2
: ( (<3|>5)
: ( (<3|>5)
& put$"Not quite, must check that Bracmat interpreter."
& put$"Not quite, must check that Bracmat interpreter."
Line 1,620: Line 1,620:
& put$"That's what I thought."
& put$"That's what I thought."
)
)
</lang>
</syntaxhighlight>


=={{header|Brainf***}}==
=={{header|Brainf***}}==
Line 1,627: Line 1,627:
Thus in the following sequence:
Thus in the following sequence:


<lang bf>[.]</lang>
<syntaxhighlight lang="bf">[.]</syntaxhighlight>


The . instruction will be skipped, while the following sequence
The . instruction will be skipped, while the following sequence


<lang bf>+[.]</lang>
<syntaxhighlight lang="bf">+[.]</syntaxhighlight>


will result in an infinite loop. Finally, in the following sequence
will result in an infinite loop. Finally, in the following sequence


<lang bf>+[.-]</lang>
<syntaxhighlight lang="bf">+[.-]</syntaxhighlight>


The . instruction will be executed once.
The . instruction will be executed once.
Line 1,643: Line 1,643:
Using the ''Choose'' command:
Using the ''Choose'' command:


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 9 2.%{"Odd""Even"}ch
blsq ) 9 2.%{"Odd""Even"}ch
"Odd"
"Odd"
</syntaxhighlight>
</lang>


Using the ''If'' command (produce next even number if odd):
Using the ''If'' command (produce next even number if odd):


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 9^^2.%{+.}if
blsq ) 9^^2.%{+.}if
10
10
blsq ) 10^^2.%{+.}if
blsq ) 10^^2.%{+.}if
10
10
</syntaxhighlight>
</lang>


Using the ''IfThenElse'' command (produce next odd number if even or previous even number if odd):
Using the ''IfThenElse'' command (produce next odd number if even or previous even number if odd):


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 10^^2.%{-.}\/{+.}\/ie
blsq ) 10^^2.%{-.}\/{+.}\/ie
11
11
blsq ) 9^^2.%{-.}\/{+.}\/ie
blsq ) 9^^2.%{-.}\/{+.}\/ie
8
8
</syntaxhighlight>
</lang>


Emulating Switch-Case behaviour:
Emulating Switch-Case behaviour:


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Banana"Fi!!
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Banana"Fi!!
"Like Bananas"
"Like Bananas"
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Apple"Fi!!
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Apple"Fi!!
"Hate Apples"
"Hate Apples"
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 1,682: Line 1,682:
===if-elseif-else===
===if-elseif-else===


<lang csharp>if (condition)
<syntaxhighlight lang="csharp">if (condition)
{
{
// Some Task
// Some Task
Line 1,698: Line 1,698:
{
{
// Some Task
// Some Task
}</lang>
}</syntaxhighlight>


===Ternary===
===Ternary===


<lang csharp>// if condition is true var will be set to 1, else 2.
<syntaxhighlight lang="csharp">// if condition is true var will be set to 1, else 2.
int var = condition ? 1 : 2;</lang>
int var = condition ? 1 : 2;</syntaxhighlight>


===switch===
===switch===


<lang csharp>switch (value)
<syntaxhighlight lang="csharp">switch (value)
{
{
case 1:
case 1:
Line 1,719: Line 1,719:
// Some task
// Some task
break;
break;
}</lang>
}</syntaxhighlight>


If fall through algorithms are required use the goto keyword.
If fall through algorithms are required use the goto keyword.


<lang csharp>switch (value)
<syntaxhighlight lang="csharp">switch (value)
{
{
case 1:
case 1:
Line 1,737: Line 1,737:
// Some task
// Some task
break;
break;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 1,752: Line 1,752:
Selecting a type depending on a compile time condition
Selecting a type depending on a compile time condition


<lang cpp>template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;
<syntaxhighlight lang="cpp">template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;


template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
Line 1,768: Line 1,768:
long int, // in that case, we'll need a long int
long int, // in that case, we'll need a long int
int> // otherwise an int will do
int> // otherwise an int will do
::type myvar; // define variable myvar with that type</lang>
::type myvar; // define variable myvar with that type</syntaxhighlight>


=={{header|Clean}}==
=={{header|Clean}}==
Line 1,774: Line 1,774:
There are no ''then'' or ''else'' keyword in Clean.
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.
The second argument of <tt>if</tt> is the then-part, the third argument is the else-part.
<lang clean>bool2int b = if b 1 0</lang>
<syntaxhighlight lang="clean">bool2int b = if b 1 0</syntaxhighlight>


===case-of===
===case-of===
<lang clean>case 6 * 7 of
<syntaxhighlight lang="clean">case 6 * 7 of
42 -> "Correct"
42 -> "Correct"
_ -> "Wrong" // default, matches anything</lang>
_ -> "Wrong" // default, matches anything</syntaxhighlight>


===function alternatives===
===function alternatives===
<lang clean>answer 42 = True
<syntaxhighlight lang="clean">answer 42 = True
answer _ = False</lang>
answer _ = False</syntaxhighlight>


===guards===
===guards===
<lang clean>answer x
<syntaxhighlight lang="clean">answer x
| x == 42 = True
| x == 42 = True
| otherwise = False
| otherwise = False
Line 1,793: Line 1,793:
n | n < 0 -> "Not even close"
n | n < 0 -> "Not even close"
42 -> "Correct"
42 -> "Correct"
// no default, could result in a run-time error</lang>
// no default, could result in a run-time error</syntaxhighlight>


=={{header|Clipper}}==
=={{header|Clipper}}==
'''if-elseif-else-endif'''
'''if-elseif-else-endif'''
<lang clipper>IF x == 1
<syntaxhighlight lang="clipper">IF x == 1
SomeFunc1()
SomeFunc1()
ELSEIF x == 2
ELSEIF x == 2
Line 1,803: Line 1,803:
ELSE
ELSE
SomeFunc()
SomeFunc()
ENDIF</lang>
ENDIF</syntaxhighlight>


'''do case'''
'''do case'''
<lang clipper>DO CASE
<syntaxhighlight lang="clipper">DO CASE
CASE x == 1
CASE x == 1
SomeFunc1()
SomeFunc1()
Line 1,813: Line 1,813:
OTHERWISE
OTHERWISE
SomeFunc()
SomeFunc()
ENDCASE</lang>
ENDCASE</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
===if-then-else===
===if-then-else===
<lang clojure>(if (= 1 1) :yes :no) ; returns :yes
<syntaxhighlight lang="clojure">(if (= 1 1) :yes :no) ; returns :yes


(if (= 1 2) :yes :no) ; returns :no
(if (= 1 2) :yes :no) ; returns :no


(if (= 1 2) :yes) ; returns nil</lang>
(if (= 1 2) :yes) ; returns nil</syntaxhighlight>


===when===
===when===
Similar to if, but body in an implicit do block allowing multiple statements.
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.
No facility for providing an else. <code>when</code> is defined as a macro.
<lang clojure>(when x
<syntaxhighlight lang="clojure">(when x
(print "hello")
(print "hello")
(println " world")
(println " world")
5) ; when x is logical true, prints "hello world" and returns 5; otherwise does nothing, returns nil</lang>
5) ; when x is logical true, prints "hello world" and returns 5; otherwise does nothing, returns nil</syntaxhighlight>


===cond===
===cond===
The cond macro takes a series of test/result pairs, evaluating each test until one resolves to logical true, then evaluates its result.
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.
Returns nil if none of the tests yield true.
<lang clojure>(cond
<syntaxhighlight lang="clojure">(cond
(= 1 2) :no) ; returns nil
(= 1 2) :no) ; returns nil


(cond
(cond
(= 1 2) :no
(= 1 2) :no
(= 1 1) :yes) ; returns :yes</lang>
(= 1 1) :yes) ; returns :yes</syntaxhighlight>
Since non-nil objects are logical true, by convention the keyword :else is used to yield a default result.
Since non-nil objects are logical true, by convention the keyword :else is used to yield a default result.
<lang clojure>(cond
<syntaxhighlight lang="clojure">(cond
(= 1 2) :no
(= 1 2) :no
:else :yes) ; returns :yes</lang>
:else :yes) ; returns :yes</syntaxhighlight>


===condp===
===condp===
Similar to cond, but useful when each test differs by only one variant.
Similar to cond, but useful when each test differs by only one variant.
<lang clojure>(condp < 3
<syntaxhighlight lang="clojure">(condp < 3
4 :a ; cond equivalent would be (< 4 3) :a
4 :a ; cond equivalent would be (< 4 3) :a
3 :b
3 :b
2 :c
2 :c
1 :d) ; returns :c</lang>
1 :d) ; returns :c</syntaxhighlight>
Optionally takes a final arg to be used as the default result if none of the tests match.
Optionally takes a final arg to be used as the default result if none of the tests match.
<lang clojure>(condp < 3
<syntaxhighlight lang="clojure">(condp < 3
4 :a
4 :a
3 :b
3 :b
:no-match) ; returns :no-match</lang>
:no-match) ; returns :no-match</syntaxhighlight>


===case===
===case===
{{Works with|Clojure|1.2}}
{{Works with|Clojure|1.2}}
<lang clojure>(case 2
<syntaxhighlight lang="clojure">(case 2
0 (println "0")
0 (println "0")
1 (println "1")
1 (println "1")
2 (println "2")) ; prints 2.</lang>
2 (println "2")) ; prints 2.</syntaxhighlight>


=={{header|CMake}}==
=={{header|CMake}}==
<lang cmake>set(num 5)
<syntaxhighlight lang="cmake">set(num 5)


if(num GREATER 100)
if(num GREATER 100)
Line 1,875: Line 1,875:
message("${num} is small.")
message("${num} is small.")
message("We might want a bigger number.")
message("We might want a bigger number.")
endif()</lang>
endif()</syntaxhighlight>


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].
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,882: Line 1,882:
=={{header|COBOL}}==
=={{header|COBOL}}==
===if-then-else===
===if-then-else===
<lang cobol>if condition-1
<syntaxhighlight lang="cobol">if condition-1
imperative-statement-1
imperative-statement-1
else
else
Line 1,900: Line 1,900:
imperative-statement-2
imperative-statement-2
end-if
end-if
end-if</lang>
end-if</syntaxhighlight>


===evaluate===
===evaluate===
<lang cobol>evaluate identifier-1
<syntaxhighlight lang="cobol">evaluate identifier-1
when 'good'
when 'good'
good-imperative-statement
good-imperative-statement
Line 1,935: Line 1,935:
when other
when other
default-imperative-statement
default-imperative-statement
end-evaluate</lang>
end-evaluate</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
Line 1,941: Line 1,941:
===if-then-else===
===if-then-else===


<lang coffeescript>
<syntaxhighlight lang="coffeescript">
if n == 1
if n == 1
console.log "one"
console.log "one"
Line 1,948: Line 1,948:
else
else
console.log "other"
console.log "other"
</syntaxhighlight>
</lang>


===switch===
===switch===


<lang coffeescript>n = 1
<syntaxhighlight lang="coffeescript">n = 1


switch n
switch n
Line 1,961: Line 1,961:
else
else
console.log "other"
console.log "other"
</syntaxhighlight>
</lang>


===ternary expressions===
===ternary expressions===
Line 1,967: Line 1,967:
CoffeeScript is very expression-oriented, so you can assign the "result" of an if-then to a variable.
CoffeeScript is very expression-oriented, so you can assign the "result" of an if-then to a variable.


<lang coffeescript>s = if condition then "yup" else "nope"
<syntaxhighlight lang="coffeescript">s = if condition then "yup" else "nope"


# alternate form
# alternate form
Line 1,973: Line 1,973:
if condition
if condition
then "yup"
then "yup"
else "nope"</lang>
else "nope"</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
===if-elseif-else===
===if-elseif-else===
'''Compiler:''' [[ColdFusion]] any version
'''Compiler:''' [[ColdFusion]] any version
<lang cfm><cfif x eq 3>
<syntaxhighlight lang="cfm"><cfif x eq 3>
do something
do something
<cfelseif x eq 4>
<cfelseif x eq 4>
Line 1,984: Line 1,984:
<cfelse>
<cfelse>
do something else
do something else
</cfif></lang>
</cfif></syntaxhighlight>


===switch===
===switch===
'''Compiler:''' [[ColdFusion]] any version
'''Compiler:''' [[ColdFusion]] any version
<lang cfm><cfswitch expression="#x#">
<syntaxhighlight lang="cfm"><cfswitch expression="#x#">
<cfcase value="1">
<cfcase value="1">
do something
do something
Line 1,998: Line 1,998:
do something
do something
</cfdefaultcase>
</cfdefaultcase>
</cfswitch></lang>
</cfswitch></syntaxhighlight>


=={{header|Comal}}==
=={{header|Comal}}==
===IF/THEN===
===IF/THEN===
<lang Comal>IF condition THEN PRINT "True"</lang>
<syntaxhighlight lang="comal">IF condition THEN PRINT "True"</syntaxhighlight>


===IF/THEN/ELSE===
===IF/THEN/ELSE===
<lang Comal>IF condition THEN
<syntaxhighlight lang="comal">IF condition THEN
PRINT "True"
PRINT "True"
ELSE
ELSE
PRINT "False"
PRINT "False"
ENDIF</lang>
ENDIF</syntaxhighlight>


===IF/THEN/ELIF/ELSE===
===IF/THEN/ELIF/ELSE===
<lang Comal>IF choice=1 THEN
<syntaxhighlight lang="comal">IF choice=1 THEN
PRINT "One"
PRINT "One"
ELIF choice=2 THEN
ELIF choice=2 THEN
PRINT "Two"
PRINT "Two"
ELSE
ELSE
Print "None of the above"</lang>
Print "None of the above"</syntaxhighlight>


===CASE/WHEN===
===CASE/WHEN===
<syntaxhighlight lang="comal">
<lang Comal>
CASE choice OF
CASE choice OF
WHEN 1
WHEN 1
Line 2,029: Line 2,029:
PRINT "Some other choice"
PRINT "Some other choice"
ENDCASE
ENDCASE
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 2,040: Line 2,040:
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.
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.


<lang lisp>(if (= val 42)
<syntaxhighlight lang="lisp">(if (= val 42)
"That is the answer to life, the universe and everything"
"That is the answer to life, the universe and everything"
"Try again") ; the else clause here is optional</lang>
"Try again") ; the else clause here is optional</syntaxhighlight>


==== <code>when</code> and <code>unless</code> ====
==== <code>when</code> and <code>unless</code> ====
Line 2,053: Line 2,053:
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.
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.


<lang lisp>(cond ((= val 1) (print "no"))
<syntaxhighlight lang="lisp">(cond ((= val 1) (print "no"))
((and (> val 3) (< val 6)) (print "yes"))
((and (> val 3) (< val 6)) (print "yes"))
((> val 99) (print "too far"))
((> val 99) (print "too far"))
(T (print "no way, man!")))</lang>
(T (print "no way, man!")))</syntaxhighlight>


=={{header|Computer/zero Assembly}}==
=={{header|Computer/zero Assembly}}==
Line 2,065: Line 2,065:
===if-elseif-else===
===if-elseif-else===


<lang crack>if (condition)
<syntaxhighlight lang="crack">if (condition)
{
{
// Some Task
// Some Task
Line 2,081: Line 2,081:
{
{
// Some Task
// Some Task
}</lang>
}</syntaxhighlight>


===Ternary===
===Ternary===


<lang crack>
<syntaxhighlight lang="crack">
// if condition is true var will be set to 1, else false.
// if condition is true var will be set to 1, else false.
int var = condition ? 1 : 2;
int var = condition ? 1 : 2;
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
:''See [[Conditional Structures#C|C]], sans the preprocessor.''
:''See [[Conditional Structures#C|C]], sans the preprocessor.''


<lang d>void main() {
<syntaxhighlight lang="d">void main() {
enum int i = 5;
enum int i = 5;


Line 2,141: Line 2,141:
// default: // Forbidden in final switches.
// default: // Forbidden in final switches.
}
}
}</lang>
}</syntaxhighlight>


=={{header|Dao}}==
=={{header|Dao}}==
===If Elif Else===
===If Elif Else===
<lang java>a = 3
<syntaxhighlight lang="java">a = 3
if( a == 1 ){
if( a == 1 ){
io.writeln( 'a == 1' )
io.writeln( 'a == 1' )
Line 2,152: Line 2,152:
}else{
}else{
io.writeln( 'a is neither 1 nor 3' )
io.writeln( 'a is neither 1 nor 3' )
}</lang>
}</syntaxhighlight>


===Switch Case===
===Switch Case===
<lang java>a = 3
<syntaxhighlight lang="java">a = 3
switch( a ){
switch( a ){
case 0: io.writeln( 'case 0' )
case 0: io.writeln( 'case 0' )
Line 2,161: Line 2,161:
case 3, 4, 5: io.writeln( 'case 3,4,5' )
case 3, 4, 5: io.writeln( 'case 3,4,5' )
default: io.writeln( 'default' )
default: io.writeln( 'default' )
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 2,169: Line 2,169:
=={{header|Deluge}}==
=={{header|Deluge}}==


<lang deluge>if (input.Field == "Hello World") {
<syntaxhighlight lang="deluge">if (input.Field == "Hello World") {
sVar = "good";
sVar = "good";
} else if (input.Field == "Bye World") {
} else if (input.Field == "Bye World") {
Line 2,175: Line 2,175:
} else {
} else {
sVar = "neutral";
sVar = "neutral";
}</lang>
}</syntaxhighlight>


=={{header|DM}}==
=={{header|DM}}==
===if-elseif-else===
===if-elseif-else===
<lang DM>if (condition)
<syntaxhighlight lang="dm">if (condition)
// Do thing, DM uses indentation for control flow.
// Do thing, DM uses indentation for control flow.


Line 2,190: Line 2,190:
else
else
// Do thing
// Do thing
</syntaxhighlight>
</lang>


===Ternary===
===Ternary===
<lang DM>// x will be 1 if condition is a true value, 2 otherwise.
<syntaxhighlight lang="dm">// x will be 1 if condition is a true value, 2 otherwise.
var/x = condition ? 1 : 2
var/x = condition ? 1 : 2
</syntaxhighlight>
</lang>


===Switch===
===Switch===
<lang DM>switch (value)
<syntaxhighlight lang="dm">switch (value)
if (0)
if (0)
// Do thing if zero
// Do thing if zero
Line 2,212: Line 2,212:
else
else
// Fallback if nothing was matched.
// Fallback if nothing was matched.
</syntaxhighlight>
</lang>


=={{header|Dragon}}==
=={{header|Dragon}}==
===if-then-else===
===if-then-else===
<lang dragon>if(a == b)
<syntaxhighlight lang="dragon">if(a == b)
{
{
add()
add()
Line 2,225: Line 2,225:
{
{
both()
both()
}</lang>
}</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
Line 2,232: Line 2,232:


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>if a:
<syntaxhighlight lang="dejavu">if a:
pass
pass
elseif b:
elseif b:
pass
pass
else: # c, maybe?
else: # c, maybe?
pass</lang>
pass</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
Line 2,243: Line 2,243:
===if-then-else===
===if-then-else===


<lang e>if (okay) {
<syntaxhighlight lang="e">if (okay) {
println("okay")
println("okay")
} else if (!okay) {
} else if (!okay) {
Line 2,249: Line 2,249:
} else {
} else {
println("not my day")
println("not my day")
}</lang>
}</syntaxhighlight>


The pick/2 message of booleans provides a value-based conditional:
The pick/2 message of booleans provides a value-based conditional:


<lang e>println(okay.pick("okay", "not okay"))</lang>
<syntaxhighlight lang="e">println(okay.pick("okay", "not okay"))</syntaxhighlight>


It can therefore be used to construct a Smalltalk-style conditional:
It can therefore be used to construct a Smalltalk-style conditional:


<lang e>okay.pick(fn {
<syntaxhighlight lang="e">okay.pick(fn {
println("okay")
println("okay")
}, fn {
}, fn {
println("not okay")
println("not okay")
})()</lang>
})()</syntaxhighlight>


All of the above conditionals are expressions and have a usable return value.
All of the above conditionals are expressions and have a usable return value.
Line 2,269: Line 2,269:
E's "switch" allows pattern matching.
E's "switch" allows pattern matching.


<lang e>def expression := ["+", [1, 2]]
<syntaxhighlight lang="e">def expression := ["+", [1, 2]]


def value := switch (expression) {
def value := switch (expression) {
Line 2,275: Line 2,275:
match [`*`, [a, b]] { a * b }
match [`*`, [a, b]] { a * b }
match [op, _] { throw(`unknown operator: $op`) }
match [op, _] { throw(`unknown operator: $op`) }
}</lang>
}</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>i = random 10
<syntaxhighlight lang="text">i = random 10
if i mod 2 = 0
if i mod 2 = 0
print i & " is divisible by 2"
print i & " is divisible by 2"
Line 2,285: Line 2,285:
else
else
print i & " is not divisible by 2 or 3"
print i & " is not divisible by 2 or 3"
.</lang>
.</syntaxhighlight>


=={{header|Efene}}==
=={{header|Efene}}==
Line 2,292: Line 2,292:
Since if and case do pattern matching, if an if or case expression don't match some of the patterns, the program will crash
Since if and case do pattern matching, if an if or case expression don't match some of the patterns, the program will crash


<lang efene>
<syntaxhighlight lang="efene">
show_if_with_parenthesis = fn (Num) {
show_if_with_parenthesis = fn (Num) {
if (Num == 1) {
if (Num == 1) {
Line 2,352: Line 2,352:
show_switch_with_parenthesis(random.uniform(3))
show_switch_with_parenthesis(random.uniform(3))
show_switch_without_parenthesis(random.uniform(3))
show_switch_without_parenthesis(random.uniform(3))
}</lang>
}</syntaxhighlight>


=={{header|Ela}}==
=={{header|Ela}}==
Line 2,358: Line 2,358:
===if-then-else===
===if-then-else===


<lang ela>if x < 0 then 0 else x</lang>
<syntaxhighlight lang="ela">if x < 0 then 0 else x</syntaxhighlight>


===Guards===
===Guards===


<lang ela>getX x | x < 0 = 0
<syntaxhighlight lang="ela">getX x | x < 0 = 0
| else = x</lang>
| else = x</syntaxhighlight>


===Pattern matching===
===Pattern matching===


<lang ela>force (x::xs) = x :: force xs
<syntaxhighlight lang="ela">force (x::xs) = x :: force xs
force [] = []</lang>
force [] = []</syntaxhighlight>


===match expression===
===match expression===


<lang ela>force lst = match lst with
<syntaxhighlight lang="ela">force lst = match lst with
x::xs = x :: force xs
x::xs = x :: force xs
[] = []</lang>
[] = []</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 2,389: Line 2,389:
case expressions take an expression and match it to a pattern with optional guards.
case expressions take an expression and match it to a pattern with optional guards.


<lang erlang>case X of
<syntaxhighlight lang="erlang">case X of
{N,M} when N > M -> M;
{N,M} when N > M -> M;
{N,M} when N < M -> N;
{N,M} when N < M -> N;
_ -> equal
_ -> equal
end.</lang>
end.</syntaxhighlight>


===if===
===if===
Line 2,400: Line 2,400:
Guards must evaluate to true or false so true is the catch-all clause.
Guards must evaluate to true or false so true is the catch-all clause.


<lang erlang>{N,M} = X,
<syntaxhighlight lang="erlang">{N,M} = X,
if
if
N > M -> M;
N > M -> M;
N < M -> N;
N < M -> N;
true -> equal
true -> equal
end.</lang>
end.</syntaxhighlight>


===Function Clauses===
===Function Clauses===
Line 2,411: Line 2,411:
Functions can have multiple clauses tested in order.
Functions can have multiple clauses tested in order.


<lang erlang>test({N,M}) when N > M -> M;
<syntaxhighlight lang="erlang">test({N,M}) when N > M -> M;
test({N,M}) when N < M -> N;
test({N,M}) when N < M -> N;
test(_) -> equal.</lang>
test(_) -> equal.</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
printfn "%s" (if 3<2 then "3 is less than 2" else "3 is not less than 2")
printfn "%s" (if 3<2 then "3 is less than 2" else "3 is not less than 2")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,431: Line 2,431:
===?===
===?===
? is for when you don't need branching, but only need to select between two different values.
? is for when you don't need branching, but only need to select between two different values.
<lang factor>
<syntaxhighlight lang="factor">
t 1 2 ? ! returns 1
t 1 2 ? ! returns 1
</syntaxhighlight>
</lang>


===if===
===if===
<lang factor>t [ 1 ] [ 2 ] if ! returns 1</lang>
<syntaxhighlight lang="factor">t [ 1 ] [ 2 ] if ! returns 1</syntaxhighlight>


===cond===
===cond===
<lang factor>{ { [ t ] [ 1 ] } { [ f ] [ 2 ] } } cond ! returns 1</lang>
<syntaxhighlight lang="factor">{ { [ t ] [ 1 ] } { [ f ] [ 2 ] } } cond ! returns 1</syntaxhighlight>


===case===
===case===
<lang factor>t { { t [ 1 ] } { f [ 2 ] } } case ! returns 1</lang>
<syntaxhighlight lang="factor">t { { t [ 1 ] } { f [ 2 ] } } case ! returns 1</syntaxhighlight>


===when===
===when===
<lang factor>t [ "1" print ] when ! prints 1</lang>
<syntaxhighlight lang="factor">t [ "1" print ] when ! prints 1</syntaxhighlight>


===unless===
===unless===
<lang factor>f [ "1" print ] unless ! prints 1</lang>
<syntaxhighlight lang="factor">f [ "1" print ] unless ! prints 1</syntaxhighlight>


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>condition[body]?</lang>
<syntaxhighlight lang="false">condition[body]?</syntaxhighlight>
Because there is no "else", you need to stash the condition if you want the same effect:
Because there is no "else", you need to stash the condition if you want the same effect:
<lang false>$[\true\]?~[false]?</lang>
<syntaxhighlight lang="false">$[\true\]?~[false]?</syntaxhighlight>
or
or
<lang false>$[%true0~]?~[false]?</lang>
<syntaxhighlight lang="false">$[%true0~]?~[false]?</syntaxhighlight>


=={{header|Fancy}}==
=={{header|Fancy}}==
Line 2,461: Line 2,461:


===if:then:===
===if:then:===
<lang fancy>if: (x < y) then: {
<syntaxhighlight lang="fancy">if: (x < y) then: {
"x < y!" println # will only execute this block if x < y
"x < y!" println # will only execute this block if x < y
}
}
</syntaxhighlight>
</lang>


===if:then:else::===
===if:then:else::===
<lang fancy>if: (x < y) then: {
<syntaxhighlight lang="fancy">if: (x < y) then: {
"x < y!" println # will only execute this block if x < y
"x < y!" println # will only execute this block if x < y
} else: {
} else: {
"x not < y!" println
"x not < y!" println
}
}
</syntaxhighlight>
</lang>




===if_true:===
===if_true:===
<lang fancy>x < y if_true: {
<syntaxhighlight lang="fancy">x < y if_true: {
"x < y!" println # will only execute this block if x < y
"x < y!" println # will only execute this block if x < y
}
}
</syntaxhighlight>
</lang>


===if_false: / if_nil:===
===if_false: / if_nil:===
<lang fancy>x < y if_false: {
<syntaxhighlight lang="fancy">x < y if_false: {
"x not < y!" println # will only execute this block if x >= y
"x not < y!" println # will only execute this block if x >= y
}
}
</syntaxhighlight>
</lang>


===if_true:else:===
===if_true:else:===
<lang fancy>x < y if_true: {
<syntaxhighlight lang="fancy">x < y if_true: {
"x < y!" println
"x < y!" println
} else: {
} else: {
"x >= y!" println
"x >= y!" println
}
}
</syntaxhighlight>
</lang>


===if_false:else:===
===if_false:else:===
<lang fancy>x < y if_false: {
<syntaxhighlight lang="fancy">x < y if_false: {
"x >= y!"
"x >= y!"
} else: {
} else: {
"x < y!" println
"x < y!" println
}
}
</syntaxhighlight>
</lang>


===if:===
===if:===
<lang fancy>{ "x < y!" println } if: (x < y) # analog, but postfix</lang>
<syntaxhighlight lang="fancy">{ "x < y!" println } if: (x < y) # analog, but postfix</syntaxhighlight>




===unless:===
===unless:===
<lang fancy>{ "x not < y!" } unless: (x < y) # same here</lang>
<syntaxhighlight lang="fancy">{ "x not < y!" } unless: (x < y) # same here</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
===IF-ELSE===
===IF-ELSE===
<lang forth>( condition ) IF ( true statements ) THEN
<syntaxhighlight lang="forth">( condition ) IF ( true statements ) THEN
( condition ) IF ( true statements ) ELSE ( false statements ) THEN</lang>
( condition ) IF ( true statements ) ELSE ( false statements ) THEN</syntaxhighlight>
example:
example:
<lang forth>10 < IF ." Less than 10" ELSE ." Greater than or equal to 10" THEN</lang>
<syntaxhighlight lang="forth">10 < IF ." Less than 10" ELSE ." Greater than or equal to 10" THEN</syntaxhighlight>


===CASE-OF===
===CASE-OF===
<lang forth>( n -- ) CASE
<syntaxhighlight lang="forth">( n -- ) CASE
( integer ) OF ( statements ) ENDOF
( integer ) OF ( statements ) ENDOF
( integer ) OF ( statements ) ENDOF
( integer ) OF ( statements ) ENDOF
( default instructions )
( default instructions )
ENDCASE</lang>
ENDCASE</syntaxhighlight>
example: a simple CASE selection
example: a simple CASE selection
<lang forth>: test-case ( n -- )
<syntaxhighlight lang="forth">: test-case ( n -- )
CASE
CASE
0 OF ." Zero!" ENDOF
0 OF ." Zero!" ENDOF
1 OF ." One!" ENDOF
1 OF ." One!" ENDOF
." Some other number!"
." Some other number!"
ENDCASE ;</lang>
ENDCASE ;</syntaxhighlight>


===Execution vector===
===Execution vector===
To obtain the efficiency of a C switch statement for enumerations, one needs to construct one's own execution vector.
To obtain the efficiency of a C switch statement for enumerations, one needs to construct one's own execution vector.
<lang forth>: switch
<syntaxhighlight lang="forth">: switch
CREATE ( default-xt [count-xts] count -- ) DUP , 0 DO , LOOP ,
CREATE ( default-xt [count-xts] count -- ) DUP , 0 DO , LOOP ,
DOES> ( u -- ) TUCK @ MIN 1+ CELLS + @ EXECUTE ;
DOES> ( u -- ) TUCK @ MIN 1+ CELLS + @ EXECUTE ;
Line 2,551: Line 2,551:


8 digit \ eight
8 digit \ eight
34 digit \ Out of range!</lang>
34 digit \ Out of range!</syntaxhighlight>
===Execution Vector 2===
===Execution Vector 2===
This method was used by the late Jim Kalihan and Dr. Julian Nobel
This method was used by the late Jim Kalihan and Dr. Julian Nobel
<lang Forth>: CASE: ( <name>) CREATE ;
<syntaxhighlight lang="forth">: CASE: ( <name>) CREATE ;


\ lookup execution token and compile
\ lookup execution token and compile
Line 2,575: Line 2,575:
===IF-THEN-ELSE===
===IF-THEN-ELSE===
ANSI FORTRAN 77 or later has an IF-THEN-ELSE structure:
ANSI FORTRAN 77 or later has an IF-THEN-ELSE structure:
<lang fortran>if ( a .gt. 20.0 ) then
<syntaxhighlight lang="fortran">if ( a .gt. 20.0 ) then
q = q + a**2
q = q + a**2
else if ( a .ge. 0.0 ) then
else if ( a .ge. 0.0 ) then
Line 2,581: Line 2,581:
else
else
q = q - a
q = q - a
end if</lang>
end if</syntaxhighlight>


===SELECT-CASE===
===SELECT-CASE===
ISO Fortran 90 or later has a SELECT-CASE structure:
ISO Fortran 90 or later has a SELECT-CASE structure:
<lang fortran>select case (i)
<syntaxhighlight lang="fortran">select case (i)
case (21:) ! matches all integers greater than 20
case (21:) ! matches all integers greater than 20
q = q + i**2
q = q + i**2
Line 2,592: Line 2,592:
case default ! matches all other integers (negative in this particular case)
case default ! matches all other integers (negative in this particular case)
q = q - I
q = q - I
end select</lang>
end select</syntaxhighlight>


===WHERE-ELSEWHERE===
===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.
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.
<lang fortran>! diffusion grid time step
<syntaxhighlight lang="fortran">! diffusion grid time step
where (edge_type(1:n,1:m) == center)
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
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,626: Line 2,626:
elsewhere ! sink/source, does not change
elsewhere ! sink/source, does not change
anew(1:n,1:m) = a(1:n,1:m)
anew(1:n,1:m) = a(1:n,1:m)
end where</lang>
end where</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
===IF-ELSEIF-ELSE-END IF===
===IF-ELSEIF-ELSE-END IF===
<lang freebasic>Dim a As Integer = 1
<syntaxhighlight lang="freebasic">Dim a As Integer = 1
If a = 1 Then
If a = 1 Then
sub1
sub1
Line 2,637: Line 2,637:
Else
Else
sub3
sub3
End If</lang>
End If</syntaxhighlight>


===SELECT-CASE===
===SELECT-CASE===
<lang freebasic>Dim a As Integer = 1
<syntaxhighlight lang="freebasic">Dim a As Integer = 1
Select Case a
Select Case a
Case 1
Case 1
Line 2,648: Line 2,648:
Case Else
Case Else
sub3
sub3
End Select</lang>
End Select</syntaxhighlight>


===IFF===
===IFF===
<lang freebasic>Dim b As Boolean = True
<syntaxhighlight lang="freebasic">Dim b As Boolean = True
Dim i As Integer = IIf(b, 1, 2)</lang>
Dim i As Integer = IIf(b, 1, 2)</syntaxhighlight>


===ON-GOTO===
===ON-GOTO===
<lang freebasic>Dim a As Integer = 1
<syntaxhighlight lang="freebasic">Dim a As Integer = 1
On a Goto label1, label2</lang>
On a Goto label1, label2</syntaxhighlight>


===IF-GOTO (deprecated)===
===IF-GOTO (deprecated)===
<lang freebasic>Dim b As Boolean = True
<syntaxhighlight lang="freebasic">Dim b As Boolean = True
If b Goto label</lang>
If b Goto label</syntaxhighlight>


===ON-GOSUB (legacy dialects only)===
===ON-GOSUB (legacy dialects only)===
<lang freebasic>Dim a As Integer = 1
<syntaxhighlight lang="freebasic">Dim a As Integer = 1
On a Gosub label1, label2</lang>
On a Gosub label1, label2</syntaxhighlight>


===#IF-#ELSEIF-#ELSE-#ENDIF (preprocessor)===
===#IF-#ELSEIF-#ELSE-#ENDIF (preprocessor)===
<lang freebasic>#DEFINE WORDSIZE 16
<syntaxhighlight lang="freebasic">#DEFINE WORDSIZE 16
#IF (WORDSIZE = 16)
#IF (WORDSIZE = 16)
' Do some some 16 bit stuff
' Do some some 16 bit stuff
Line 2,674: Line 2,674:
#ELSE
#ELSE
#ERROR WORDSIZE must be set to 16 or 32
#ERROR WORDSIZE must be set to 16 or 32
#ENDIF</lang>
#ENDIF</syntaxhighlight>


===#IFDEF (preprocessor)===
===#IFDEF (preprocessor)===
<lang freebasic>#DEFINE _DEBUG
<syntaxhighlight lang="freebasic">#DEFINE _DEBUG
#IFDEF _DEBUG
#IFDEF _DEBUG
' Special statements for debugging
' Special statements for debugging
#ENDIF</lang>
#ENDIF</syntaxhighlight>


===#IFNDEF (preprocessor)===
===#IFNDEF (preprocessor)===
<lang freebasic>#IFNDEF _DEBUG
<syntaxhighlight lang="freebasic">#IFNDEF _DEBUG
#DEFINE _DEBUG
#DEFINE _DEBUG
#ENDIF</lang>
#ENDIF</syntaxhighlight>


=={{header|friendly interactive shell}}==
=={{header|friendly interactive shell}}==
===if-then-else===
===if-then-else===
<lang fishshell>set var 'Hello World'
<syntaxhighlight lang="fishshell">set var 'Hello World'
if test $var = 'Hello World'
if test $var = 'Hello World'
echo 'Welcome.'
echo 'Welcome.'
Line 2,696: Line 2,696:
else
else
echo 'Huh?'
echo 'Huh?'
end</lang>
end</syntaxhighlight>


===switch===
===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.
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.
<lang fishshell>switch actually
<syntaxhighlight lang="fishshell">switch actually
case az
case az
echo The word is "az".
echo The word is "az".
Line 2,711: Line 2,711:
case '*'
case '*'
echo Neither begins with a or ends with z.
echo Neither begins with a or ends with z.
end</lang>
end</syntaxhighlight>


=={{header|Futhark}}==
=={{header|Futhark}}==
Line 2,718: Line 2,718:
Futhark supports branching with a syntax common to most functional languages.
Futhark supports branching with a syntax common to most functional languages.


<lang futhark>
<syntaxhighlight lang="futhark">
if <condition> then <truebranch> else <falsebranch>
if <condition> then <truebranch> else <falsebranch>
</syntaxhighlight>
</lang>


=={{header|GAP}}==
=={{header|GAP}}==
=== if-then-else ===
=== if-then-else ===
<lang gap>if <condition> then
<syntaxhighlight lang="gap">if <condition> then
<statements>
<statements>
elif <condition> then
elif <condition> then
Line 2,730: Line 2,730:
else
else
<statements>
<statements>
fi;</lang>
fi;</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 2,736: Line 2,736:
===If===
===If===
Simplest usage is,
Simplest usage is,
<lang go>if booleanExpression {
<syntaxhighlight lang="go">if booleanExpression {
statements
statements
}</lang>
}</syntaxhighlight>
The braces are required, even around a single statement.
The braces are required, even around a single statement.
<lang go>if booleanExpression {
<syntaxhighlight lang="go">if booleanExpression {
statements
statements
} else {
} else {
other
other
statements
statements
}</lang>
}</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,
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,
<lang go>if booleanExpression1 {
<syntaxhighlight lang="go">if booleanExpression1 {
statements
statements
} else if booleanExpression2 {
} else if booleanExpression2 {
otherStatements
otherStatements
}
}
</syntaxhighlight>
</lang>
If allows a statement to be included ahead of the condition. This is commonly a short variable declaration, as in,
If allows a statement to be included ahead of the condition. This is commonly a short variable declaration, as in,
<lang go>if x := fetchSomething(); x > 0 {
<syntaxhighlight lang="go">if x := fetchSomething(); x > 0 {
DoPos(x)
DoPos(x)
} else {
} else {
DoNeg(x)
DoNeg(x)
}</lang>
}</syntaxhighlight>
In this case the scope of x is limited to if statement.
In this case the scope of x is limited to if statement.


===Switch===
===Switch===
Simple usage is,
Simple usage is,
<lang go>switch {
<syntaxhighlight lang="go">switch {
case booleanExpression1:
case booleanExpression1:
statements
statements
Line 2,773: Line 2,773:
resort
resort
statements
statements
}</lang>
}</syntaxhighlight>
Because switch can work with any number of arbitrary boolean expressions, it replaces if/elseif chains often found in other programming languages.
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,
Switch can also switch on the value of an expression, as in,
<lang go>switch expressionOfAnyType {
<syntaxhighlight lang="go">switch expressionOfAnyType {
case value1:
case value1:
statements
statements
Line 2,783: Line 2,783:
other
other
statements
statements
}</lang>
}</syntaxhighlight>
As shown, multiple values can be listed for a single case clause.
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.
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:
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:
<lang go>switch x := fetch(); {
<syntaxhighlight lang="go">switch x := fetch(); {
case x == "cheese":
case x == "cheese":
statements
statements
Line 2,794: Line 2,794:
other
other
statements
statements
}</lang>
}</syntaxhighlight>
Also, as with if, the scope of x is limited to the switch statement.
Also, as with if, the scope of x is limited to the switch statement.


Line 2,800: Line 2,800:


An interesting example:
An interesting example:
<lang go>switch {
<syntaxhighlight lang="go">switch {
case booleanExpression1:
case booleanExpression1:
default:
default:
Line 2,809: Line 2,809:
other
other
statements
statements
}</lang>
}</syntaxhighlight>
Case expressions are evaluated in order, then if none are true, the default clause is executed.
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.
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.
<lang go>for {
<syntaxhighlight lang="go">for {
switch {
switch {
case true:
case true:
Line 2,819: Line 2,819:
}
}
fmt.Println("I want out!")
fmt.Println("I want out!")
}</lang>
}</syntaxhighlight>
Labels provide the desired capability. The following prints "I'm off!"
Labels provide the desired capability. The following prints "I'm off!"
<lang go>treadmill: for {
<syntaxhighlight lang="go">treadmill: for {
switch {
switch {
case true:
case true:
Line 2,827: Line 2,827:
}
}
}
}
fmt.Println("I'm off!")</lang>
fmt.Println("I'm off!")</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
'''if-elseif-else-endif'''
'''if-elseif-else-endif'''
<lang visualfoxpro>IF x == 1
<syntaxhighlight lang="visualfoxpro">IF x == 1
SomeFunc1()
SomeFunc1()
ELSEIF x == 2
ELSEIF x == 2
Line 2,837: Line 2,837:
ELSE
ELSE
SomeFunc()
SomeFunc()
ENDIF</lang>
ENDIF</syntaxhighlight>


'''do case'''
'''do case'''
<lang visualfoxpro>DO CASE
<syntaxhighlight lang="visualfoxpro">DO CASE
CASE x == 1
CASE x == 1
SomeFunc1()
SomeFunc1()
Line 2,847: Line 2,847:
OTHERWISE
OTHERWISE
SomeFunc()
SomeFunc()
ENDCASE</lang>
ENDCASE</syntaxhighlight>


'''switch'''
'''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.
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.
<lang visualfoxpro>SWITCH x
<syntaxhighlight lang="visualfoxpro">SWITCH x
CASE 1
CASE 1
SomeFunc1()
SomeFunc1()
Line 2,860: Line 2,860:
OTHERWISE
OTHERWISE
SomeFunc()
SomeFunc()
ENDSWITCH</lang>
ENDSWITCH</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==


===if-then-else===
===if-then-else===
<lang haskell>fac x = if x==0 then
<syntaxhighlight lang="haskell">fac x = if x==0 then
1
1
else x * fac (x - 1)</lang>
else x * fac (x - 1)</syntaxhighlight>


===Guards===
===Guards===
<lang haskell>fac x | x==0 = 1
<syntaxhighlight lang="haskell">fac x | x==0 = 1
| x>0 = x * fac (x-1)</lang>
| x>0 = x * fac (x-1)</syntaxhighlight>
===Pattern matching===
===Pattern matching===
<lang haskell>fac 0 = 1
<syntaxhighlight lang="haskell">fac 0 = 1
fac x = x * fac (x-1)</lang>
fac x = x * fac (x-1)</syntaxhighlight>
===case statement===
===case statement===
<lang haskell>fac x = case x of 0 -> 1
<syntaxhighlight lang="haskell">fac x = case x of 0 -> 1
_ -> x * fac (x-1)</lang>
_ -> x * fac (x-1)</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>IF( a > 5 ) WRITE(Messagebox) a ! single line IF
<syntaxhighlight lang="hicest">IF( a > 5 ) WRITE(Messagebox) a ! single line IF


IF( a >= b ) THEN
IF( a >= b ) THEN
Line 2,890: Line 2,890:
ELSE
ELSE
WRITE(StatusBar) a, b, some_string
WRITE(StatusBar) a, b, some_string
ENDIF</lang>
ENDIF</syntaxhighlight>


=={{header|HPPPL}}==
=={{header|HPPPL}}==
=== IF ===
=== IF ===
Note that X has to be a number; else a runtime error occurs.
Note that X has to be a number; else a runtime error occurs.
<lang HPPPL>IF X THEN
<syntaxhighlight lang="hpppl">IF X THEN
// do if X is not 0
// do if X is not 0
ELSE
ELSE
// do if X is 0
// do if X is 0
END;</lang>
END;</syntaxhighlight>
=== CASE ===
=== CASE ===
<lang HPPPL>CASE
<syntaxhighlight lang="hpppl">CASE
IF X == 1 THEN
IF X == 1 THEN
// do stuff if X equals 1
// do stuff if X equals 1
Line 2,913: Line 2,913:
DEFAULT
DEFAULT
// do other stuff
// do other stuff
END;</lang>
END;</syntaxhighlight>


=={{header|i}}==
=={{header|i}}==
<lang i>//'i' supports if, else, and else if
<syntaxhighlight lang="i">//'i' supports if, else, and else if
software {
software {
a = 3
a = 3
Line 2,927: Line 2,927:
print("a = ", a)
print("a = ", a)
end
end
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 2,933: Line 2,933:
===if-then-else===
===if-then-else===
The control structure evaluates expr1 if expr0 succeeds and expr2 if it fails.
The control structure evaluates expr1 if expr0 succeeds and expr2 if it fails.
<lang Icon>if expr0 then
<syntaxhighlight lang="icon">if expr0 then
expr1
expr1
else
else
expr2</lang>
expr2</syntaxhighlight>
===case-of===
===case-of===
The first successful selection expression will select and evaluate the specific case.
The first successful selection expression will select and evaluate the specific case.
<lang Icon>case expr0 of {
<syntaxhighlight lang="icon">case expr0 of {
expr1 : expr2
expr1 : expr2
expr3 : expr4
expr3 : expr4
default: expr5
default: expr5
}</lang>
}</syntaxhighlight>
Note that expr1 and expr3 are expressions and not constants and it is possible to write expressions such as:
Note that expr1 and expr3 are expressions and not constants and it is possible to write expressions such as:
<lang Icon>case x of {
<syntaxhighlight lang="icon">case x of {
f(x) | g(x) : expr2
f(x) | g(x) : expr2
s(x) & t(x) : expr4
s(x) & t(x) : expr4
default: expr5
default: expr5
}</lang>
}</syntaxhighlight>
===Compound expressions (blocks)===
===Compound expressions (blocks)===
In the examples below, multiple expressions can be grouped as in:
In the examples below, multiple expressions can be grouped as in:
<syntaxhighlight lang="icon">{
<lang Icon>{
expr1
expr1
expr2
expr2
expr3
expr3
}</lang>
}</syntaxhighlight>
Which is equivalent to this:
Which is equivalent to this:
<lang Icon>{expr1; expr2; expr3}</lang>
<syntaxhighlight lang="icon">{expr1; expr2; expr3}</syntaxhighlight>
For example the following, which will write 4, looks strange but is valid:
For example the following, which will write 4, looks strange but is valid:
<lang Icon>write({1;2;3;4})</lang>
<syntaxhighlight lang="icon">write({1;2;3;4})</syntaxhighlight>
The value of a compound expression is the value of the last expression in the block.
The value of a compound expression is the value of the last expression in the block.
===Alternation===
===Alternation===
Alternation of expressions yields a value for the first succeeding expression.
Alternation of expressions yields a value for the first succeeding expression.
<lang Icon> expr1 | expr2 | expr3</lang>
<syntaxhighlight lang="icon"> expr1 | expr2 | expr3</syntaxhighlight>
===Conjunction===
===Conjunction===
Conjunctions yeild the value of the final expression provided all the previous expressions succeed.
Conjunctions yeild the value of the final expression provided all the previous expressions succeed.
<lang Icon> expr1 & expr2 & expr3</lang>
<syntaxhighlight lang="icon"> expr1 & expr2 & expr3</syntaxhighlight>
Alternately, conjunction can be written thus:
Alternately, conjunction can be written thus:
<lang Icon> (expr1, expr2, expr3)</lang>
<syntaxhighlight lang="icon"> (expr1, expr2, expr3)</syntaxhighlight>
===Conjunction, yielding a different result===
===Conjunction, yielding a different result===
The alternate form of conjunction can be modified to produce a different result (other than the last)
The alternate form of conjunction can be modified to produce a different result (other than the last)
<lang Icon> expr0(expr1, expr2, expr3)</lang>
<syntaxhighlight lang="icon"> expr0(expr1, expr2, expr3)</syntaxhighlight>
For example:
For example:
<lang Icon> 2(expr1, expr2, expr3)</lang>
<syntaxhighlight lang="icon"> 2(expr1, expr2, expr3)</syntaxhighlight>
Yields the value of expr2 if all of the expressions succeed.
Yields the value of expr2 if all of the expressions succeed.
<br>A more complicated example showing non-constant expressions:
<br>A more complicated example showing non-constant expressions:
<lang Icon> f(expr1)(g(expr2)(expr3,expr4,expr5))</lang>
<syntaxhighlight lang="icon"> f(expr1)(g(expr2)(expr3,expr4,expr5))</syntaxhighlight>
Note: if expr0 yields a value of type 'procedure' or 'string' the appropriate procedure (or operator) is invoked.
Note: if expr0 yields a value of type 'procedure' or 'string' the appropriate procedure (or operator) is invoked.


Line 2,986: Line 2,986:
Basic if/then:
Basic if/then:


<lang idl>if a eq 5 then print, "a equals five" [else print, "a is something else"]</lang>
<syntaxhighlight lang="idl">if a eq 5 then print, "a equals five" [else print, "a is something else"]</syntaxhighlight>


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:
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:


<lang idl>if a eq 5 then begin
<syntaxhighlight lang="idl">if a eq 5 then begin
... some code here ...
... some code here ...
endif [else begin
endif [else begin
... some other code here ...
... some other code here ...
endelse]</lang>
endelse]</syntaxhighlight>


===case===
===case===


<lang idl>case <expression> of
<syntaxhighlight lang="idl">case <expression> of
(choice-1): <command-1>
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[(choice-2): <command-2> [...]]
[else: <command-else>]
[else: <command-else>]
endcase</lang>
endcase</syntaxhighlight>


(Or replace any of the commands with {begin..end} pairs)
(Or replace any of the commands with {begin..end} pairs)
Line 3,008: Line 3,008:
===switch===
===switch===


<lang idl>switch <expression> of
<syntaxhighlight lang="idl">switch <expression> of
(choice-1): <command-1>
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[(choice-2): <command-2> [...]]
[else: <command-else>]
[else: <command-else>]
endswitch</lang>
endswitch</syntaxhighlight>


The <tt>switch</tt> will execute all commands starting with the matching result, while the <tt>case</tt> will only execute the matching one.
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,018: Line 3,018:
===on_error===
===on_error===


<lang idl>on_error label</lang>
<syntaxhighlight lang="idl">on_error label</syntaxhighlight>


Will resume execution at label when an error is encountered. <tt>on_ioerror</tt> is similar but for IO errors.
Will resume execution at label when an error is encountered. <tt>on_ioerror</tt> is similar but for IO errors.
Line 3,024: Line 3,024:
=={{header|Inform 7}}==
=={{header|Inform 7}}==
===if-then-else===
===if-then-else===
<lang inform7>[short form]
<syntaxhighlight lang="inform7">[short form]
if N is 1, say "one.";
if N is 1, say "one.";
otherwise say "not one.";
otherwise say "not one.";
Line 3,037: Line 3,037:


[short and long forms can be negated with "unless"]
[short and long forms can be negated with "unless"]
unless N is 1, say "not one."</lang>
unless N is 1, say "not one."</syntaxhighlight>


===switch===
===switch===
<lang inform7>if N is:
<syntaxhighlight lang="inform7">if N is:
-- 1: say "one.";
-- 1: say "one.";
-- 2: say "two.";
-- 2: say "two.";
-- otherwise: say "not one or two.";</lang>
-- otherwise: say "not one or two.";</syntaxhighlight>


===if-then-else in text===
===if-then-else in text===
<lang inform7>say "[if N is 1]one[otherwise if N is 2]two[otherwise]three[end if].";
<syntaxhighlight 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]";</lang>
say "[unless N is odd]even.[end if]";</syntaxhighlight>


===other branching text substitutions===
===other branching text substitutions===
Text that may be printed multiple times can also use sequential and random branching:
Text that may be printed multiple times can also use sequential and random branching:
<lang inform7>[a different color every time]
<syntaxhighlight lang="inform7">[a different color every time]
say "[one of]red[or]blue[or]green[at random].";
say "[one of]red[or]blue[or]green[at random].";


Line 3,058: Line 3,058:


[only appears once]
[only appears once]
say "[first time]Hello world![only]";</lang>
say "[first time]Hello world![only]";</syntaxhighlight>


===rulebook approach===
===rulebook approach===
Conditional logic may also be expressed in the form of a rulebook, with conditions on each rule:
Conditional logic may also be expressed in the form of a rulebook, with conditions on each rule:


<lang inform7>Number Factory is a room.
<syntaxhighlight lang="inform7">Number Factory is a room.


Number handling is a number based rulebook with default success.
Number handling is a number based rulebook with default success.
Line 3,075: Line 3,075:
follow the number handling rules for 2;
follow the number handling rules for 2;
follow the number handling rules for 4;
follow the number handling rules for 4;
follow the number handling rules for 5.</lang>
follow the number handling rules for 5.</syntaxhighlight>


=={{header|Isabelle}}==
=={{header|Isabelle}}==
<lang Isabelle>theory Scratch
<syntaxhighlight lang="isabelle">theory Scratch
imports Main
imports Main
begin
begin
Line 3,099: Line 3,099:
lemma "recurse n = 0" by(induction n) simp+
lemma "recurse n = 0" by(induction n) simp+


end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 3,106: Line 3,106:
=={{header|Java}}==
=={{header|Java}}==
===if-then-else===
===if-then-else===
<lang java>if(s.equals("Hello World"))
<syntaxhighlight lang="java">if(s.equals("Hello World"))
{
{
foo();
foo();
Line 3,115: Line 3,115:
{
{
deusEx();
deusEx();
}</lang>
}</syntaxhighlight>
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
<lang java>if(obj != null && obj.foo()){
<syntaxhighlight lang="java">if(obj != null && obj.foo()){
aMethod();
aMethod();
}</lang>
}</syntaxhighlight>
<tt>obj.foo()</tt> will not be executed if <tt>obj != null</tt> returns false. It is possible to have conditionals without short circuit evaluation using the <tt>&</tt> and <tt>|</tt> operators (from [[Bitwise operations]]). So in this conditional:
<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:
<lang java>if(obj != null & obj.foo()){
<syntaxhighlight lang="java">if(obj != null & obj.foo()){
aMethod();
aMethod();
}</lang>
}</syntaxhighlight>
You will get a null pointer exception if obj is null.
You will get a null pointer exception if obj is null.
===ternary===
===ternary===


<lang java>s.equals("Hello World") ? foo() : bar();</lang>
<syntaxhighlight lang="java">s.equals("Hello World") ? foo() : bar();</syntaxhighlight>


===switch===
===switch===
This structure will only work if the code being switched on evaluates to an integer or character. There is no switching on Objects or floating-point types in Java (except for <code>String</code>s in Java 7 and higher).
This structure will only work if the code being switched on evaluates to an integer or character. There is no switching on Objects or floating-point types in Java (except for <code>String</code>s in Java 7 and higher).
<lang java>switch(c) {
<syntaxhighlight lang="java">switch(c) {
case 'a':
case 'a':
foo();
foo();
Line 3,139: Line 3,139:
default:
default:
foobar();
foobar();
}</lang>
}</syntaxhighlight>
This particular example can show the "fallthrough" behavior of a switch statement. If c is the character b, then bar() and foobar() will both be called. If c is the character a, only foo() will be called because of the break statement at the end of that case.
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:
Also, the switch statement can be easily translated into an if-else if-else statement. The example above is equivalent to:
<lang java>if(c == 'a'){
<syntaxhighlight lang="java">if(c == 'a'){
foo();
foo();
}else if(c == 'b'){
}else if(c == 'b'){
Line 3,150: Line 3,150:
}else{
}else{
foobar();
foobar();
}</lang>
}</syntaxhighlight>
Cases without breaks at the end require duplication of code for all cases underneath them until a break is found (like the else if block shown here).
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).


Line 3,157: Line 3,157:
===if-then-else===
===if-then-else===


<lang javascript>if( s == "Hello World" ) {
<syntaxhighlight lang="javascript">if( s == "Hello World" ) {
foo();
foo();
} else if( s == "Bye World" ) {
} else if( s == "Bye World" ) {
Line 3,163: Line 3,163:
} else {
} else {
deusEx();
deusEx();
}</lang>
}</syntaxhighlight>


===switch===
===switch===


<lang javascript>switch(object) {
<syntaxhighlight lang="javascript">switch(object) {
case 1:
case 1:
one();
one();
Line 3,181: Line 3,181:
default:
default:
everythingElse();
everythingElse();
}</lang>
}</syntaxhighlight>


===conditional (ternary) operator (?:)===
===conditional (ternary) operator (?:)===


<lang javascript>var num = window.obj ? obj.getNumber() : null;</lang>
<syntaxhighlight lang="javascript">var num = window.obj ? obj.getNumber() : null;</syntaxhighlight>


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.
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.


<lang JavaScript>function takeWhile(lst, fnTest) {
<syntaxhighlight lang="javascript">function takeWhile(lst, fnTest) {
'use strict';
'use strict';
var varHead = lst.length ? lst[0] : null;
var varHead = lst.length ? lst[0] : null;
Line 3,198: Line 3,198:
) : []
) : []
) : [];
) : [];
}</lang>
}</syntaxhighlight>


=={{header|JCL}}==
=={{header|JCL}}==
Line 3,211: Line 3,211:
</pre>
</pre>
The syntax of COND parameter of the EXEC statement is :
The syntax of COND parameter of the EXEC statement is :
<lang jcl> COND=(rcval,relop,step)
<syntaxhighlight lang="jcl"> COND=(rcval,relop,step)
relop is a relational opeator : EQ NE GT LT GE LE (= ¬= < > <= >=) </lang>
relop is a relational opeator : EQ NE GT LT GE LE (= ¬= < > <= >=) </syntaxhighlight>
It is a condition to bypass a job step, and it can be translateted into :
It is a condition to bypass a job step, and it can be translateted into :
<lang jcl> if rcval relop step.rc then not execute the current step </lang>
<syntaxhighlight lang="jcl"> if rcval relop step.rc then not execute the current step </syntaxhighlight>
Example:
Example:
<lang jcl>//STEP6 EXEC PGM=MYPROG,COND=(0,NE,STEP3)</lang>
<syntaxhighlight lang="jcl">//STEP6 EXEC PGM=MYPROG,COND=(0,NE,STEP3)</syntaxhighlight>
<pre>
<pre>
if 0 ne STEP3.rc then skip step STEP6
if 0 ne STEP3.rc then skip step STEP6
Line 3,224: Line 3,224:
</pre>
</pre>
The conditions can be multiple :
The conditions can be multiple :
<lang jcl> COND=((rcval1,relop1,step1),(rcval2,relop2,step2),...) </lang>
<syntaxhighlight lang="jcl"> COND=((rcval1,relop1,step1),(rcval2,relop2,step2),...) </syntaxhighlight>
Means:
Means:
<lang jcl> if rcval1 relop1 step1.rc or rcval2 relop2 step2.rc or ... then not execute the current step </lang>
<syntaxhighlight lang="jcl"> if rcval1 relop1 step1.rc or rcval2 relop2 step2.rc or ... then not execute the current step </syntaxhighlight>
Example:
Example:
<lang jcl>//STEP6 EXEC PGM=MYPROG,COND=((4,LE,STEP1),(8,LE,STEP3)) </lang>
<syntaxhighlight lang="jcl">//STEP6 EXEC PGM=MYPROG,COND=((4,LE,STEP1),(8,LE,STEP3)) </syntaxhighlight>
<pre>
<pre>
if 4 le STEP1.rc or 8 le STEP3.rc then skip step STEP6
if 4 le STEP1.rc or 8 le STEP3.rc then skip step STEP6
Line 3,239: Line 3,239:
===if-then-else===
===if-then-else===


<lang jinja>
<syntaxhighlight lang="jinja">
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{% if loop.last %}.{% else %},{% endif %}
{{ loop.index }}) {{ lang }}{% if loop.last %}.{% else %},{% endif %}
{%- endfor %}""").render())
{%- endfor %}""").render())
</syntaxhighlight>
</lang>


===ternary expressions===
===ternary expressions===


<lang jinja>
<syntaxhighlight lang="jinja">
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{{ "." if loop.last else "," }}
{{ loop.index }}) {{ lang }}{{ "." if loop.last else "," }}
{%- endfor %}""").render())
{%- endfor %}""").render())
</syntaxhighlight>
</lang>


===short-circuit evaluation===
===short-circuit evaluation===


<lang jinja>
<syntaxhighlight lang="jinja">
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{{ loop.last and "." or "," }}
{{ loop.index }}) {{ lang }}{{ loop.last and "." or "," }}
{%- endfor %}""").render())
{%- endfor %}""").render())
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
jq's main conditional construct is:<lang jq>if cond then f else g end</lang>where cond, f, and g, are filters, and where cond may evaluate to anything at all, it being understood that:
jq's main conditional construct is:<syntaxhighlight lang="jq">if cond then f else g end</syntaxhighlight>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;
# 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.
# 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:
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
if cond then f elif cond1 then f1 .... else g end
</syntaxhighlight>
</lang>


For example:<lang jq>
For example:<syntaxhighlight lang="jq">
if empty then 2 else 3 end # produces no value
if empty then 2 else 3 end # produces no value
if 1 then 2 else 3 end # produces 2
if 1 then 2 else 3 end # produces 2
if [false, false] 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
if (true, true) then 2 else 3 end # produces a stream: 2, 2
</lang>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.
</syntaxhighlight>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:<lang jq>
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:<syntaxhighlight lang="jq">
exp
exp
| if . == true then "true"
| if . == true then "true"
Line 3,285: Line 3,285:
elif type == "string" then .
elif type == "string" then .
else error("unexpected value: \(.)")
else error("unexpected value: \(.)")
end</lang>
end</syntaxhighlight>
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 `//`.
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,291: Line 3,291:
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
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>
<h3>Conditional Evaluation</h3>
<syntaxhighlight lang="julia">
<lang Julia>
function test(x, y)
function test(x, y)
if x < y
if x < y
Line 3,310: Line 3,310:
julia> test(1, 1)
julia> test(1, 1)
x is equal to y
x is equal to y
</syntaxhighlight>
</lang>
<p>
<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.
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>
</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:
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><lang Julia>
</p><syntaxhighlight lang="julia">
a ? b : c
a ? b : c
</syntaxhighlight>
</lang>
<p>
<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.
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,332: Line 3,332:
=={{header|Kabap}}==
=={{header|Kabap}}==
Kabap supports the '''if''' statement and a range of standard comparators. Truthiness is considered anything not "0" or 0.
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;
if 1;
$result = "Execute";
$result = "Execute";
Line 3,388: Line 3,388:
}
}


</syntaxhighlight>
</lang>


=={{header|Keg}}==
=={{header|Keg}}==
Keg supports if statements like this:
Keg supports if statements like this:
<lang keg>?A>[The letter is larger than a|The letter is smaller than a]</lang>
<syntaxhighlight lang="keg">?A>[The letter is larger than a|The letter is smaller than a]</syntaxhighlight>
Usually the ending proprotions may be omitted:
Usually the ending proprotions may be omitted:
<lang keg>?![You did enter something]</lang>
<syntaxhighlight lang="keg">?![You did enter something]</syntaxhighlight>


Also Keg supports (though not intentionally) a form of short-circuit evaluation:
Also Keg supports (though not intentionally) a form of short-circuit evaluation:
<lang keg>2?1>*# Returns 2 if the input is larger than 1</lang>
<syntaxhighlight lang="keg">2?1>*# Returns 2 if the input is larger than 1</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 3,427: Line 3,427:
}
}
println("$i is $t")
println("$i is $t")
}</lang>
}</syntaxhighlight>
Sample input/output (program invoked without arguments):
Sample input/output (program invoked without arguments):
{{out}}
{{out}}
Line 3,447: Line 3,447:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{if true then yes else no}
{if true then yes else no}
-> yes
-> yes
Line 3,465: Line 3,465:
{switch 0}
{switch 0}
-> 0 is zero
-> 0 is zero
</syntaxhighlight>
</lang>


=={{header|langur}}==
=={{header|langur}}==
Line 3,474: Line 3,474:
===if expressions===
===if expressions===
If expressions are scoped per section.
If expressions are scoped per section.
<lang langur># using the fact that submatch() returns an empty array for no match ...
<syntaxhighlight lang="langur"># using the fact that submatch() returns an empty array for no match ...
# ... and that a decoupling assignment returns a Boolean...
# ... and that a decoupling assignment returns a Boolean...


Line 3,487: Line 3,487:
val .y = 70
val .y = 70
...
...
}</lang>
}</syntaxhighlight>


Prior to langur 0.10, you would use parentheses around the declared variable names (.alias, .name).
Prior to langur 0.10, you would use parentheses around the declared variable names (.alias, .name).
Line 3,496: Line 3,496:
This is more flexible than a ternary operator, as it allows more than one test. An else section is optional (null by default).
This is more flexible than a ternary operator, as it allows more than one test. An else section is optional (null by default).


<lang langur>if(.x > .y: ...; .x < .y: ...; /* else */ ...)</lang>
<syntaxhighlight lang="langur">if(.x > .y: ...; .x < .y: ...; /* else */ ...)</syntaxhighlight>


===if statements===
===if statements===
Langur 0.7.1 added "if statements," using 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.
Langur 0.7.1 added "if statements," using 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.


<lang langur>if .x > .y: break</lang>
<syntaxhighlight lang="langur">if .x > .y: break</syntaxhighlight>


===given expressions===
===given expressions===
Line 3,508: Line 3,508:
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.
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.


<lang langur>given .x, .y, .z {
<syntaxhighlight lang="langur">given .x, .y, .z {
case true: ...
case true: ...
# all are true
# all are true
Line 3,515: Line 3,515:
case _, null, true: ...
case _, null, true: ...
# .y == null and .z == true
# .y == null and .z == true
}</lang>
}</syntaxhighlight>


As of 0.7, complex test expressions are evaluated once, then compared against conditions.
As of 0.7, complex test expressions are evaluated once, then compared against conditions.
Line 3,521: Line 3,521:
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".
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 {
<syntaxhighlight lang="langur">given .x, .y, != .z {
case 7 <, 14, 21: ...
case 7 <, 14, 21: ...
# 7 < .x and .y == 14 and 21 != .z
# 7 < .x and .y == 14 and 21 != .z
Line 3,535: Line 3,535:


default: ...
default: ...
}</lang>
}</syntaxhighlight>


===implicit fallthrough===
===implicit fallthrough===
If a block of a given has any statements, there is no implicit fallthrough. A case with an empty block after it creates an implicit fallthrough.
If a block of a given has any statements, there is no implicit fallthrough. A case with an empty block after it creates an implicit fallthrough.
<lang langur>given .x {
<syntaxhighlight lang="langur">given .x {
case true:
case true:
# implicit fallthrough
# implicit fallthrough
Line 3,545: Line 3,545:
# no fallthrough
# no fallthrough
default: 1
default: 1
}</lang>
}</syntaxhighlight>


===explicit fallthrough from anywhere===
===explicit fallthrough from anywhere===
A fallthrough statement is allowed anywhere within a given block, not just at the end.
A fallthrough statement is allowed anywhere within a given block, not just at the end.
<lang langur>given .x {
<syntaxhighlight lang="langur">given .x {
case true:
case true:
if .y > 100 {
if .y > 100 {
Line 3,557: Line 3,557:
}
}
case false: ...
case false: ...
}</lang>
}</syntaxhighlight>


===shortened form given===
===shortened form given===
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).
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).
<lang langur>given(.x, .y, .z;
<syntaxhighlight lang="langur">given(.x, .y, .z;
true: ... ; # all are equal to true
true: ... ; # all are equal to true
_, >= .z: ...; # .y >= .z
_, >= .z: ...; # .y >= .z
... ) # default</lang>
... ) # default</syntaxhighlight>


=={{header|LC3 Assembly}}==
=={{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.
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.
<lang lc3asm>BR or BRnzp ; unconditional branch, i.e.
<syntaxhighlight lang="lc3asm">BR or BRnzp ; unconditional branch, i.e.
; branch if (result < 0 || result == 0 || result > 0)
; branch if (result < 0 || result == 0 || result > 0)
; ^ this is always true
; ^ this is always true
Line 3,577: Line 3,577:


; or any combination of these condition codes, e.g.
; or any combination of these condition codes, e.g.
BRnz ; branch if (result <= 0)</lang>
BRnz ; branch if (result <= 0)</syntaxhighlight>
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.
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.
<lang lc3asm>.orig x3000
<syntaxhighlight lang="lc3asm">.orig x3000
LD R1, x ; get x
LD R1, x ; get x
LD R2, y ; get y
LD R2, y ; get y
Line 3,597: Line 3,597:
taken .stringz "Branch Taken!"
taken .stringz "Branch Taken!"
nottaken .stringz "Branch Not Taken!"
nottaken .stringz "Branch Not Taken!"
.end</lang>
.end</syntaxhighlight>


=={{header|LIL}}==
=={{header|LIL}}==
LIL sports '''if''' with an optional code block for else conditions.
LIL sports '''if''' with an optional code block for else conditions.


<lang tcl>if {$a > 10} {print "code evaluated on true"}
<syntaxhighlight lang="tcl">if {$a > 10} {print "code evaluated on true"}
if {$a > 10} {print "again"} {print "code evaluated on false"}</lang>
if {$a > 10} {print "again"} {print "code evaluated on false"}</syntaxhighlight>


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.
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,612: Line 3,612:
{{works with|Lisaac|0.13.1}}
{{works with|Lisaac|0.13.1}}
===if-then-else===
===if-then-else===
<lang Lisaac>+ n : INTEGER;
<syntaxhighlight lang="lisaac">+ n : INTEGER;


n := 3;
n := 3;
Line 3,624: Line 3,624:
} else {
} else {
IO.put_string "n is none of the above\n";
IO.put_string "n is none of the above\n";
};</lang>
};</syntaxhighlight>
<lang Lisaac>(n = 2).if_true { "n is 2\n".print; };
<syntaxhighlight lang="lisaac">(n = 2).if_true { "n is 2\n".print; };
(n = 2).if_false { "n is not 2\n".print; };</lang>
(n = 2).if_false { "n is not 2\n".print; };</syntaxhighlight>
===when===
===when===
<lang Lisaac>+ n : INTEGER;
<syntaxhighlight lang="lisaac">+ n : INTEGER;


n := 3;
n := 3;
Line 3,640: Line 3,640:
.when 4 then {
.when 4 then {
"n is 4\n".print;
"n is 4\n".print;
};</lang>
};</syntaxhighlight>
There is no "else" or "otherwise" method.
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.
If the values of the when-methods are overlapped, the related blocks will be evaluated ... they are not mutually exclusive.
Line 3,646: Line 3,646:
=={{header|Little}}==
=={{header|Little}}==


<lang C>int a = 3;
<syntaxhighlight lang="c">int a = 3;


// if-then-else
// if-then-else
Line 3,679: Line 3,679:
default:
default:
puts("is neither");
puts("is neither");
}</lang>
}</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>if :x < 0 [make "x 0 - :x]
<syntaxhighlight lang="logo">if :x < 0 [make "x 0 - :x]


ifelse emptyp :list [print [empty]] [print :list]</lang>
ifelse emptyp :list [print [empty]] [print :list]</syntaxhighlight>
[[UCB Logo]] and its descendants have also case:
[[UCB Logo]] and its descendants have also case:
<lang logo>to vowel? :letter
<syntaxhighlight lang="logo">to vowel? :letter
output case :letter [ [[a e i o u] "true] [else "false] ]
output case :letter [ [[a e i o u] "true] [else "false] ]
end
end
show vowel? "e
show vowel? "e
show vowel? "x</lang>
show vowel? "x</syntaxhighlight>
{{out}}
{{out}}
<lang logo>true
<syntaxhighlight lang="logo">true
false</lang>
false</syntaxhighlight>
Logo also provides TEST which is local to a procedure:
Logo also provides TEST which is local to a procedure:
<lang logo>to mytest :arg1 :arg2
<syntaxhighlight lang="logo">to mytest :arg1 :arg2
test :arg1 = :arg2
test :arg1 = :arg2
iftrue [print [Arguments are equal]]
iftrue [print [Arguments are equal]]
iffalse [print [Arguments are not equal]]
iffalse [print [Arguments are not equal]]
end</lang>
end</syntaxhighlight>


=={{header|LSE}}==
=={{header|LSE}}==
==={{header|SI..ALORS..SINON..FIN SI}}===
==={{header|SI..ALORS..SINON..FIN SI}}===
<lang LSE>SI A ET B ALORS
<syntaxhighlight lang="lse">SI A ET B ALORS
AFFICHER [4X, 'A ET B = .VRAI.',/]
AFFICHER [4X, 'A ET B = .VRAI.',/]
SINON
SINON
Line 3,712: Line 3,712:
SINON
SINON
AFFICHER [4X, 'A ET QUE B = .FAUX.',/]
AFFICHER [4X, 'A ET QUE B = .FAUX.',/]
FIN SI</lang>
FIN SI</syntaxhighlight>


==={{header|EVALUER}}===
==={{header|EVALUER}}===
<lang LSE>EVALUER X
<syntaxhighlight lang="lse">EVALUER X
QUAND 0
QUAND 0
AFFICHER [4X,'QUAND X=0',/]
AFFICHER [4X,'QUAND X=0',/]
Line 3,724: Line 3,724:
QUAND AUTRE
QUAND AUTRE
AFFICHER [4X,'QUAND X est autre, X=',U,/] X
AFFICHER [4X,'QUAND X est autre, X=',U,/] X
FIN EVALUER</lang>
FIN EVALUER</syntaxhighlight>


==={{header|SELON..ALLER EN..}}===
==={{header|SELON..ALLER EN..}}===
<lang LSE>0 AFFICHER [U,/] 'Faites votre choix:'
<syntaxhighlight lang="lse">0 AFFICHER [U,/] 'Faites votre choix:'
1 AFFICHER [8X,U,X,/] '0 VACHES'
1 AFFICHER [8X,U,X,/] '0 VACHES'
2 AFFICHER [8X,U,/] '1 MOUTONS'
2 AFFICHER [8X,U,/] '1 MOUTONS'
Line 3,734: Line 3,734:
10 AFFICHER [U,/] 'Vous avez choisi VACHES!'
10 AFFICHER [U,/] 'Vous avez choisi VACHES!'
15 TERMINER
15 TERMINER
20 AFFICHER [U,/] 'Vous avez choisi MOUTONS!'</lang>
20 AFFICHER [U,/] 'Vous avez choisi MOUTONS!'</syntaxhighlight>


==={{header|SI..ALORS..SINON..IS}}===
==={{header|SI..ALORS..SINON..IS}}===
<lang LSE>ENTIER U <- SI A ALORS 65535 SINON 1 IS</lang>
<syntaxhighlight lang="lse">ENTIER U <- SI A ALORS 65535 SINON 1 IS</syntaxhighlight>


==={{header|SELON..DANS..SINON..FIN}}===
==={{header|SELON..DANS..SINON..FIN}}===
<lang LSE>ENTIER U <- SELON A DANS 0, 255 SINON 1 FIN</lang>
<syntaxhighlight lang="lse">ENTIER U <- SELON A DANS 0, 255 SINON 1 FIN</syntaxhighlight>


=={{header|LSE64}}==
=={{header|LSE64}}==
The simple conditionals take single words rather than blocks of statements, as in most other languages.
The simple conditionals take single words rather than blocks of statements, as in most other languages.
<lang lse64>t : " true" ,t
<syntaxhighlight lang="lse64">t : " true" ,t
f : " false" ,t
f : " false" ,t
true if t
true if t
false ifnot f
false ifnot f
true ifelse t f</lang>
true ifelse t f</syntaxhighlight>


Cascading conditionals are constructed using duplicate definitions and "then", yielding a syntax reminiscent of functional language [[Pattern Matching]].
Cascading conditionals are constructed using duplicate definitions and "then", yielding a syntax reminiscent of functional language [[Pattern Matching]].
<lang lse64>onetwo : drop " Neither one nor two" ,t # default declared first
<syntaxhighlight lang="lse64">onetwo : drop " Neither one nor two" ,t # default declared first
onetwo : dup 2 = then " Two" ,t
onetwo : dup 2 = then " Two" ,t
onetwo : dup 1 = then " One" ,t</lang>
onetwo : dup 1 = then " One" ,t</syntaxhighlight>


Short-circuit operators "&&" and "||" are used for complex conditionals.
Short-circuit operators "&&" and "||" are used for complex conditionals.
<lang lse64>dup 0 = || ,t # avoid printing a null string</lang>
<syntaxhighlight lang="lse64">dup 0 = || ,t # avoid printing a null string</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
--if-then-elseif-then-else
--if-then-elseif-then-else
if a then
if a then
Line 3,791: Line 3,791:
}
}


cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively</lang>
cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively</syntaxhighlight>


=={{header|Luna}}==
=={{header|Luna}}==


===if-then-else===
===if-then-else===
<lang luna>if char == "<" then Prepend "<" acc else acc</lang>
<syntaxhighlight lang="luna">if char == "<" then Prepend "<" acc else acc</syntaxhighlight>
''(see: [https://github.com/luna/luna/issues/125#issuecomment-365683922 github/luna #125])''
''(see: [https://github.com/luna/luna/issues/125#issuecomment-365683922 github/luna #125])''


===case-of===
===case-of===
<lang luna>class JSON:
<syntaxhighlight lang="luna">class JSON:
...
...
def asText: case self of:
def asText: case self of:
JSONString t: t
JSONString t: t
other: throw "JSON.asText: not a text"</lang>
other: throw "JSON.asText: not a text"</syntaxhighlight>


''(see: [https://github.com/luna/luna/blob/77b1d974cb07528e9f195dd47e177dd497560da1/stdlib/Std/src/Base.luna#L1047-L1050 Std.JSON])''
''(see: [https://github.com/luna/luna/blob/77b1d974cb07528e9f195dd47e177dd497560da1/stdlib/Std/src/Base.luna#L1047-L1050 Std.JSON])''
Line 3,810: Line 3,810:
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
===If Then Else.if Else===
===If Then Else.if Else===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Read a
Read a
Line 3,848: Line 3,848:
CheckIt 0
CheckIt 0
CheckIt -100
CheckIt -100
</syntaxhighlight>
</lang>


===IF() and IF$() - Ternary===
===IF() and IF$() - Ternary===
One expression evaluated only. We can use If$() to use string expressions
One expression evaluated only. We can use If$() to use string expressions
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Read x
Read x
Line 3,869: Line 3,869:
Checkit 3, 20
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.
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 {
Module Checkit {
def a
def a
Line 3,887: Line 3,887:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


===Select Case===
===Select Case===
We can use string, and three types of cases (all of them in one case), >1000, 10 to 40, 400
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 {
Module CheckIt {
Read a
Read a
Line 3,933: Line 3,933:
CheckIt -500
CheckIt -500


</syntaxhighlight>
</lang>


===Conditional loops===
===Conditional loops===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
x=10
x=10
While x>0 {
While x>0 {
Line 3,958: Line 3,958:
Until x=10
Until x=10


</syntaxhighlight>
</lang>


===On Goto, On Gosub===
===On Goto, On Gosub===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
For i=1 to 10 {
For i=1 to 10 {
Line 3,992: Line 3,992:
CheckIt
CheckIt


</syntaxhighlight>
</lang>
===If Then line No /label===
===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).
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"
a$="123"
if a$ ~ "12*" then 1000
if a$ ~ "12*" then 1000
Line 4,004: Line 4,004:
1000 Print "ok final"
1000 Print "ok final"
Goto alfa
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()
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 4,010: Line 4,010:
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 ="
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 {
Module Checkit {
Rem : Dim beta(10) ' remove Rem to get error when call beta() without Gosub
Rem : Dim beta(10) ' remove Rem to get error when call beta() without Gosub
Line 4,031: Line 4,031:
Checkit
Checkit


</syntaxhighlight>
</lang>


=={{header|Make}}==
=={{header|Make}}==
An if condition using pure make (no gmake extensions)
An if condition using pure make (no gmake extensions)
<lang make># make -f do.mk C=mycond if
<syntaxhighlight lang="make"># make -f do.mk C=mycond if
C=0
C=0


Line 4,046: Line 4,046:


false:
false:
@echo "was false."</lang>
@echo "was false."</syntaxhighlight>


Using it
Using it
<lang make>make -f do.mk if C=0
<syntaxhighlight lang="make">make -f do.mk if C=0
> was false.
> was false.


make -f do.mk if C=1
make -f do.mk if C=1
> was true.</lang>
> was true.</syntaxhighlight>


With out using recursion but letting make continue with non-failed
With out using recursion but letting make continue with non-failed
targets even when some of the targets failed (-k)
targets even when some of the targets failed (-k)
<lang make>C=0
<syntaxhighlight lang="make">C=0


if: true false
if: true false
Line 4,067: Line 4,067:
false:
false:
@expr $(C) >/dev/null && exit 1 || exit 0
@expr $(C) >/dev/null && exit 1 || exit 0
@echo "was false."</lang>
@echo "was false."</syntaxhighlight>


Invoking it. Note the use of -k which allows make to evaluate subsequent
Invoking it. Note the use of -k which allows make to evaluate subsequent
targets even when a previous non-related target failed.
targets even when a previous non-related target failed.
<lang make>|make -f do.mk -s -k C=1
<syntaxhighlight lang="make">|make -f do.mk -s -k C=1
was true.
was true.
*** Error code 1
*** Error code 1
|make -f do.mk -s -k C=0
|make -f do.mk -s -k C=0
*** Error code 1
*** Error code 1
was false.</lang>
was false.</syntaxhighlight>


Using gmake
Using gmake


<lang make>A=
<syntaxhighlight lang="make">A=
B=
B=


Line 4,090: Line 4,090:


do:
do:
@echo $(A) .. $(B)</lang>
@echo $(A) .. $(B)</syntaxhighlight>


Using it
Using it
<lang make>|gmake -f if.mk A=1
<syntaxhighlight lang="make">|gmake -f if.mk A=1
1 .. true
1 .. true
|gmake -f if.mk A=0
|gmake -f if.mk A=0
0 .. false</lang>
0 .. false</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
Line 4,103: Line 4,103:
=== Conditional statements ===
=== Conditional statements ===
Example syntax for conditional statements:
Example syntax for conditional statements:
<lang Maple>if x > 0 then
<syntaxhighlight lang="maple">if x > 0 then
res := x;
res := x;
else
else
res := -x;
res := -x;
end if;</lang>
end if;</syntaxhighlight>


Example syntax for conditional statements with else-if:
Example syntax for conditional statements with else-if:
<lang Maple>if x = 0 then
<syntaxhighlight lang="maple">if x = 0 then
res := y;
res := y;
elif y = 0 then
elif y = 0 then
Line 4,116: Line 4,116:
else
else
res := sqrt(x^2+y^2);
res := sqrt(x^2+y^2);
end if;</lang>
end if;</syntaxhighlight>


=== Conditional functions ===
=== Conditional functions ===
Line 4,141: Line 4,141:
===If statements===
===If statements===
Example:
Example:
<lang MATLAB>if x == 1
<syntaxhighlight lang="matlab">if x == 1
disp 'x==1';
disp 'x==1';
elseif x > 1
elseif x > 1
Line 4,147: Line 4,147:
else
else
disp 'x<1';
disp 'x<1';
end</lang>
end</syntaxhighlight>
===Switch statements===
===Switch statements===
Example:
Example:
<lang MATLAB>switch x
<syntaxhighlight lang="matlab">switch x
case 1
case 1
disp 'Hello';
disp 'Hello';
Line 4,157: Line 4,157:
otherwise
otherwise
disp 'Skynet Active';
disp 'Skynet Active';
end</lang>
end</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>if test1 then (...) elseif test2 then (...) else (...);</lang>
<syntaxhighlight lang="maxima">if test1 then (...) elseif test2 then (...) else (...);</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
===if===
===if===
<lang maxscript>if x == 1 then
<syntaxhighlight lang="maxscript">if x == 1 then
(
(
print "one"
print "one"
Line 4,175: Line 4,175:
(
(
print "Neither one or two"
print "Neither one or two"
)</lang>
)</syntaxhighlight>


===case===
===case===
'''Form one'''
'''Form one'''
<lang maxscript>case x of
<syntaxhighlight lang="maxscript">case x of
(
(
1: (print "one")
1: (print "one")
2: (print "two")
2: (print "two")
default: (print "Neither one or two")
default: (print "Neither one or two")
)</lang>
)</syntaxhighlight>
'''Form two'''
'''Form two'''
<lang maxscript>case of
<syntaxhighlight lang="maxscript">case of
(
(
(x == 1): (print "one")
(x == 1): (print "one")
(x == 2): (print "two")
(x == 2): (print "two")
default: (print "Neither one or two")
default: (print "Neither one or two")
)</lang>
)</syntaxhighlight>


=={{header|MBS}}==
=={{header|MBS}}==


<lang MBS>INT x;
<syntaxhighlight lang="mbs">INT x;
x:=0;
x:=0;
IF x = 1 THEN
IF x = 1 THEN
Line 4,201: Line 4,201:
ELSE
ELSE
! Do something else
! Do something else
ENDIF;</lang>
ENDIF;</syntaxhighlight>


=={{header|MDL}}==
=={{header|MDL}}==
Line 4,211: Line 4,211:
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.
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.


<lang MDL><COND (<==? .X 1> <PRINC "one">)
<syntaxhighlight lang="mdl"><COND (<==? .X 1> <PRINC "one">)
(<==? .X 2> <PRINC "two">)
(<==? .X 2> <PRINC "two">)
(T <PRINC "something else">)></lang>
(T <PRINC "something else">)></syntaxhighlight>


===AND and OR===
===AND and OR===
Line 4,219: Line 4,219:
These short-circuiting boolean functions can also be used as simple conditionals.
These short-circuiting boolean functions can also be used as simple conditionals.


<lang MDL>;"Negate X if its value is less than 0"
<syntaxhighlight lang="mdl">;"Negate X if its value is less than 0"
<AND <L? .X 0> <SET X <- .X>>>
<AND <L? .X 0> <SET X <- .X>>>


;"Print a message unless the quiet flag is set"
;"Print a message unless the quiet flag is set"
<OR .QUIET? <PRINC "Finished">></lang>
<OR .QUIET? <PRINC "Finished">></syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==


<lang metafont>if conditionA:
<syntaxhighlight lang="metafont">if conditionA:
% do something
% do something
elseif conditionB:
elseif conditionB:
Line 4,234: Line 4,234:
else:
else:
% do this
% do this
fi;</lang>
fi;</syntaxhighlight>


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
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


<lang metafont>b := if a > 5: 3 + else: 2 - fi c;</lang>
<syntaxhighlight lang="metafont">b := if a > 5: 3 + else: 2 - fi c;</syntaxhighlight>


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
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,247: Line 4,247:
=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<lang min>(true) ("I'm true") ("I'm false") if ; If first quotation evaluates to true,
<syntaxhighlight lang="min">(true) ("I'm true") ("I'm false") if ; If first quotation evaluates to true,
; evaluate second quotation.
; evaluate second quotation.
; Otherwise, evaluate the third.
; Otherwise, evaluate the third.
Line 4,258: Line 4,258:
((3 <) ("Smaller than 3" puts!)) ; quotation if the first quotation
((3 <) ("Smaller than 3" puts!)) ; quotation if the first quotation
((true) ("Exactly 3" puts!)) ; evaluates to true. Otherwise, move
((true) ("Exactly 3" puts!)) ; evaluates to true. Otherwise, move
) case ; on to the next one.</lang>
) case ; on to the next one.</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
MiniScript supports if/else-if/else, with arbitrary number of else-if sections when in block form:
MiniScript supports if/else-if/else, with arbitrary number of else-if sections when in block form:


<lang MiniScript>x = 42
<syntaxhighlight lang="miniscript">x = 42
if x < 10 then
if x < 10 then
print "small"
print "small"
Line 4,272: Line 4,272:
else
else
print "just right"
print "just right"
end if</lang>
end if</syntaxhighlight>


It also supports single-line if or if/else statements (though no else-if sections are permitted in this case):
It also supports single-line if or if/else statements (though no else-if sections are permitted in this case):


<lang MiniScript>x = 42
<syntaxhighlight lang="miniscript">x = 42
if x < 50 then print "small" else print "big"</lang>
if x < 50 then print "small" else print "big"</syntaxhighlight>


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.
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.


<lang MiniScript>isSmall = function(x)
<syntaxhighlight lang="miniscript">isSmall = function(x)
print "checking smallness"
print "checking smallness"
return x < 40
return x < 40
Line 4,291: Line 4,291:
end function
end function


isSmall(10) or isBig(100)</lang>
isSmall(10) or isBig(100)</syntaxhighlight>


{{out}}
{{out}}
Line 4,299: Line 4,299:
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.
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===
===If/Else===
<lang mips>BEQ $t0,$t1,Label ;branch to label if $t0 = $t1. If not, fallthrough to the instruction after the delay slot.
<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</lang>
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:
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:


<lang mips>addu $t0,$t1 ;I'm going to branch based off this addition, but there's other things I want to do first.
<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)
lw $t3,($t4)
nop ;load delay slot
nop ;load delay slot
BEQ $t0,$t1,Label
BEQ $t0,$t1,Label
nop ;branch delay slot</lang>
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:
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:


<lang mips>BNEZ $t0,loop ;branch if $t0 is nonzero.
<syntaxhighlight lang="mips">BNEZ $t0,loop ;branch if $t0 is nonzero.
subiu $t0,1 ;this finishes at the same time the jumpback occurs.</lang>
subiu $t0,1 ;this finishes at the same time the jumpback occurs.</syntaxhighlight>


MIPS also comes with greater than/less than constructs built-in.
MIPS also comes with greater than/less than constructs built-in.
Line 4,323: Line 4,323:
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!''
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!''


<lang mips>BGEU $t0,$t1,label ;branch if $t0 >= $t1, treating both as unsigned.
<syntaxhighlight lang="mips">BGEU $t0,$t1,label ;branch if $t0 >= $t1, treating both as unsigned.
NOP
NOP
BLT $t7,$t3,label ;branch if $t7 < $t3, treating both as signed
BLT $t7,$t3,label ;branch if $t7 < $t3, treating both as signed
NOP</lang>
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.
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.
Line 4,333: Line 4,333:
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.
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.


<lang mips>switchExample:
<syntaxhighlight lang="mips">switchExample:
;this implementation assumes that all destinations end in jr ra, so you'll need to arrive here with JAL 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.)
;$t0 = index (must be a multiple of 4 or the program counter will jump to a location that's not guaranteed to properly return.)
Line 4,358: Line 4,358:
baz:
baz:
;code goes here
;code goes here
jr ra</lang>
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.
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.
Line 4,365: Line 4,365:
Conditional jumps are done by four instructions, comparing the register X with zero:
Conditional jumps are done by four instructions, comparing the register X with zero:


<lang>x=0 XX
<syntaxhighlight lang="text">x=0 XX
x#0 XX
x#0 XX
x>=0 XX
x>=0 XX
x<0 XX</lang>
x<0 XX</syntaxhighlight>


'''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).
'''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,374: Line 4,374:
=={{header|Modula-2}}==
=={{header|Modula-2}}==
===if-then-else===
===if-then-else===
<lang modula2>IF i = 1 THEN
<syntaxhighlight lang="modula2">IF i = 1 THEN
InOut.WriteString('One')
InOut.WriteString('One')
ELSIF i = 2 THEN
ELSIF i = 2 THEN
Line 4,382: Line 4,382:
ELSE
ELSE
InOut.WriteString('Other')
InOut.WriteString('Other')
END;</lang>
END;</syntaxhighlight>


===Case===
===Case===
<lang modula2>CASE i OF
<syntaxhighlight lang="modula2">CASE i OF
1 : InOut.WriteString('One')
1 : InOut.WriteString('One')
| 2 : InOut.WriteString('Two')
| 2 : InOut.WriteString('Two')
Line 4,391: Line 4,391:
ELSE
ELSE
InOut.WriteString('Other')
InOut.WriteString('Other')
END</lang>
END</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
===if-then-else===
===if-then-else===
<lang modula3>IF Foo = TRUE THEN
<syntaxhighlight lang="modula3">IF Foo = TRUE THEN
Bar();
Bar();
ELSE
ELSE
Baz();
Baz();
END;</lang>
END;</syntaxhighlight>


<lang modula3>IF Foo = "foo" THEN
<syntaxhighlight lang="modula3">IF Foo = "foo" THEN
Bar();
Bar();
ELSIF Foo = "bar" THEN
ELSIF Foo = "bar" THEN
Line 4,409: Line 4,409:
ELSE
ELSE
Zeepf();
Zeepf();
END;</lang>
END;</syntaxhighlight>


===Case===
===Case===
<lang modula3>CASE Foo OF
<syntaxhighlight lang="modula3">CASE Foo OF
| 1 => IO.Put("One\n");
| 1 => IO.Put("One\n");
| 2 => IO.Put("Two\n");
| 2 => IO.Put("Two\n");
Line 4,418: Line 4,418:
ELSE
ELSE
IO.Put("Something\n");
IO.Put("Something\n");
END;</lang>
END;</syntaxhighlight>
===Type-case===
===Type-case===
<tt>TYPECASE</tt> is used on reference types to perform different operations, depending on what it is a reference to.
<tt>TYPECASE</tt> is used on reference types to perform different operations, depending on what it is a reference to.
<lang modula3>TYPECASE ref OF
<syntaxhighlight lang="modula3">TYPECASE ref OF
| NULL => IO.Put("Null\n");
| NULL => IO.Put("Null\n");
| CHAR => IO.Put("Char\n");
| CHAR => IO.Put("Char\n");
Line 4,427: Line 4,427:
ELSE
ELSE
IO.Put("Something\n");
IO.Put("Something\n");
END;</lang>
END;</syntaxhighlight>


=={{header|Monicelli}}==
=={{header|Monicelli}}==
Monicelli has a single conditional structure that covers both if/then/else and switch/case
Monicelli has a single conditional structure that covers both if/then/else and switch/case
<lang monicelli>
<syntaxhighlight lang="monicelli">
che cosè var? # switch var
che cosè var? # switch var
minore di 0: # case var < 0
minore di 0: # case var < 0
Line 4,440: Line 4,440:
...
...
e velocità di esecuzione
e velocità di esecuzione
</syntaxhighlight>
</lang>


=={{header|Morfa}}==
=={{header|Morfa}}==
===if-then-else===
===if-then-else===
<lang morfa>
<syntaxhighlight lang="morfa">
if(s == "Hello World")
if(s == "Hello World")
{
{
Line 4,455: Line 4,455:
baz();
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:
Morfa supports [[wp:Short-circuit_evaluation|short-circuit evaluation]], so <tt>obj.foo()</tt> won't be executed if <tt>obj</tt> is null:
<lang morfa>
<syntaxhighlight lang="morfa">
if(obj isnt null and obj.foo())
if(obj isnt null and obj.foo())
doSomething();
doSomething();
</syntaxhighlight>
</lang>


===ternary===
===ternary===
<lang morfa>
<syntaxhighlight lang="morfa">
var t = if(s == "Hello World") foo() else bar();
var t = if(s == "Hello World") foo() else bar();
</syntaxhighlight>
</lang>


===switch===
===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.
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.
<lang morfa>
<syntaxhighlight lang="morfa">
switch (num)
switch (num)
{
{
Line 4,481: Line 4,481:
result = "a lot";
result = "a lot";
}
}
</syntaxhighlight>
</lang>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
===If / I and ELSE / E===
===If / I and ELSE / E===
<lang MUMPS> IF A list-of-MUMPS-commands</lang>
<syntaxhighlight lang="mumps"> IF A list-of-MUMPS-commands</syntaxhighlight>
<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.
<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:
For example with the code:
<lang MUMPS> IF T DO SUBROUTINE
<syntaxhighlight lang="mumps"> IF T DO SUBROUTINE
ELSE DO SOMETHING</lang>
ELSE DO SOMETHING</syntaxhighlight>
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 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:
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
IF T DO SUBROUTINE IF 1
ELSE DO SOMETHING</lang>
ELSE DO SOMETHING</syntaxhighlight>


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:
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
IF T DO
. DO SUBROUTINE
. DO SUBROUTINE
ELSE DO SOMETHING</lang>
ELSE DO SOMETHING</syntaxhighlight>




Line 4,509: Line 4,509:


===$Select / $S===
===$Select / $S===
<lang MUMPS> WRITE $SELECT(1=2:"Unequal",1=3:"More unequal",1:"Who cares?")</lang>
<syntaxhighlight lang="mumps"> WRITE $SELECT(1=2:"Unequal",1=3:"More unequal",1:"Who cares?")</syntaxhighlight>
<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.
<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>
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/:===
===(command postconditional i.e. colon/:===
<lang MUMPS> SET:(1=1) SKY="Blue"
<syntaxhighlight lang="mumps"> SET:(1=1) SKY="Blue"
GOTO:ReallyGo LABEL
GOTO:ReallyGo LABEL
QUIT:LoopDone
QUIT:LoopDone
WRITE:NotLastInSet ","</lang>
WRITE:NotLastInSet ","</syntaxhighlight>
<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>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.
<p>The exceptions are FOR, IF, and ELSE.
Line 4,536: Line 4,536:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
===if-then-else===
===if-then-else===
<lang nanoquery>if x = 0
<syntaxhighlight lang="nanoquery">if x = 0
foo()
foo()
else if x = 1
else if x = 1
Line 4,544: Line 4,544:
else
else
boz()
boz()
end</lang>
end</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
===if-else===
===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.
<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.
<lang Nemerle>if (the_answer == 42) FindQuestion() else Foo();
<syntaxhighlight lang="nemerle">if (the_answer == 42) FindQuestion() else Foo();
when (stock.price < buy_order) stock.Buy();
when (stock.price < buy_order) stock.Buy();
unless (text < "") Write(text);</lang>
unless (text < "") Write(text);</syntaxhighlight>


===match===
===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].
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].
<lang Nemerle>match(x)
<syntaxhighlight lang="nemerle">match(x)
{
{
|1 => "x is one"
|1 => "x is one"
|x when (x < 5) => "x is less than five"
|x when (x < 5) => "x is less than five"
|_ => "x is at least five"
|_ => "x is at least five"
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
===IF-THEN-ELSE===
===IF-THEN-ELSE===
<lang NetRexx>-- simple construct
<syntaxhighlight lang="netrexx">-- simple construct
if logicalCondition then conditionWasTrue()
if logicalCondition then conditionWasTrue()
else conditionWasFalse()
else conditionWasFalse()
Line 4,597: Line 4,597:
conditionsWereFalse()
conditionsWereFalse()
...
...
end</lang>
end</syntaxhighlight>


===SELECT===
===SELECT===
Line 4,606: Line 4,606:


<tt>OTHERWISE</tt> is optional but may result in run-time errors (<tt>netrexx.lang.NoOtherwiseException</tt>) if it isn't provided.
<tt>OTHERWISE</tt> is optional but may result in run-time errors (<tt>netrexx.lang.NoOtherwiseException</tt>) if it isn't provided.
<lang NetRexx>-- simple construct
<syntaxhighlight lang="netrexx">-- simple construct
select
select
when logicalCondition1 then condition1()
when logicalCondition1 then condition1()
Line 4,621: Line 4,621:
catch ex1 = NoOtherwiseException
catch ex1 = NoOtherwiseException
ex1.printStackTrace()
ex1.printStackTrace()
end</lang>
end</syntaxhighlight>


===SELECT-CASE===
===SELECT-CASE===
<lang NetRexx>-- simple construct
<syntaxhighlight lang="netrexx">-- simple construct
select case cc
select case cc
when 'A' then say 'the case is A'
when 'A' then say 'the case is A'
when 'B' then say 'the case is B'
when 'B' then say 'the case is B'
otherwise say 'selection not recognized'
otherwise say 'selection not recognized'
end</lang>
end</syntaxhighlight>


'''Note:''' This is functionally equivalent to:
'''Note:''' This is functionally equivalent to:
<lang NetRexx>select
<syntaxhighlight lang="netrexx">select
when cc == 'A' then ...
when cc == 'A' then ...
when cc == 'B' then ...
when cc == 'B' then ...
...</lang>
...</syntaxhighlight>


===SELECT Optional Features===
===SELECT Optional Features===
Line 4,648: Line 4,648:


<tt>PROTECT</tt> is used for program concurrency &amp; synchonization in multi-threaded programs.
<tt>PROTECT</tt> is used for program concurrency &amp; synchonization in multi-threaded programs.
<lang NetRexx>select label sl protect cc case cc
<syntaxhighlight lang="netrexx">select label sl protect cc case cc
when 'A' then do
when 'A' then do
say 'the case is A'
say 'the case is A'
Line 4,667: Line 4,667:
say 'selection done'
say 'selection done'
say 'TTFN'
say 'TTFN'
end sl</lang>
end sl</syntaxhighlight>


=={{header|newLISP}}==
=={{header|newLISP}}==
===if===
===if===
'''Interpreter:''' [[newLISP]] v.9.0
'''Interpreter:''' [[newLISP]] v.9.0
<lang lisp>(set 'x 1)
<syntaxhighlight lang="lisp">(set 'x 1)
(if (= x 1) (println "is 1"))</lang>
(if (= x 1) (println "is 1"))</syntaxhighlight>
A third expression can be used as an else.
A third expression can be used as an else.
<lang lisp>(set 'x 0)
<syntaxhighlight lang="lisp">(set 'x 0)
(if (= x 1) (println "is 1") (println "not 1"))</lang>
(if (= x 1) (println "is 1") (println "not 1"))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
===if-then-else===
===if-then-else===
<lang nim>if x == 0:
<syntaxhighlight lang="nim">if x == 0:
foo()
foo()
elif x == 1:
elif x == 1:
Line 4,687: Line 4,687:
baz()
baz()
else:
else:
boz()</lang>
boz()</syntaxhighlight>


===case-of===
===case-of===
<lang nim>case x
<syntaxhighlight lang="nim">case x
of 0:
of 0:
foo()
foo()
Line 4,698: Line 4,698:
baz()
baz()
else: # All cases must be covered
else: # All cases must be covered
boz()</lang>
boz()</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
===if-else===
===if-else===
<lang objeck>
<syntaxhighlight lang="objeck">
a := GetValue();
a := GetValue();
if(a < 5) {
if(a < 5) {
Line 4,713: Line 4,713:
"equal to 5"->PrintLine();
"equal to 5"->PrintLine();
};
};
</syntaxhighlight>
</lang>


===select===
===select===
<lang objeck>
<syntaxhighlight lang="objeck">
a := GetValue();
a := GetValue();
select(a) {
select(a) {
Line 4,731: Line 4,731:
}
}
};
};
</syntaxhighlight>
</lang>


=={{header|Object Pascal}}==
=={{header|Object Pascal}}==
Line 4,744: Line 4,744:
===if-then-else===
===if-then-else===


<lang ocaml>let condition = true
<syntaxhighlight lang="ocaml">let condition = true


if condition then
if condition then
1 (* evaluate something *)
1 (* evaluate something *)
else
else
2 (* evaluate something *)</lang>
2 (* evaluate something *)</syntaxhighlight>


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:
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:


<lang ocaml>if condition then begin
<syntaxhighlight lang="ocaml">if condition then begin
(); (* evaluate things for side effects *)
(); (* evaluate things for side effects *)
5
5
Line 4,760: Line 4,760:
(); (* evaluate things for side effects *)
(); (* evaluate things for side effects *)
42
42
end</lang>
end</syntaxhighlight>


===match-with===
===match-with===
<lang ocaml>match expression with
<syntaxhighlight lang="ocaml">match expression with
| 0 -> () (* evaluate something *)
| 0 -> () (* evaluate something *)
| 1 -> () (* evaluate something *)
| 1 -> () (* evaluate something *)
| n when n mod 2 = 0 -> () (* evaluate something *)
| n when n mod 2 = 0 -> () (* evaluate something *)
| _ -> () (* evaluate something *)</lang>
| _ -> () (* evaluate something *)</syntaxhighlight>


The first <tt>|</tt> is optional, and usually omitted.
The first <tt>|</tt> is optional, and usually omitted.
Line 4,777: Line 4,777:
=={{header|Octave}}==
=={{header|Octave}}==
'''if-then-elseif-else'''
'''if-then-elseif-else'''
<lang octave>if (condition)
<syntaxhighlight lang="octave">if (condition)
% body
% body
endif
endif
Line 4,793: Line 4,793:
else
else
% otherwise body
% otherwise body
endif</lang>
endif</syntaxhighlight>


'''switch'''
'''switch'''
<lang octave>switch( expression )
<syntaxhighlight lang="octave">switch( expression )
case label1
case label1
% code for label1
% code for label1
Line 4,803: Line 4,803:
otherwise
otherwise
% none of the previous
% none of the previous
endswitch</lang>
endswitch</syntaxhighlight>


''Labels'' can be numeric or string, or cells to group several possibilities:
''Labels'' can be numeric or string, or cells to group several possibilities:


<lang octave>switch ( x )
<syntaxhighlight lang="octave">switch ( x )
case 1
case 1
disp("it is 1");
disp("it is 1");
Line 4,814: Line 4,814:
otherwise
otherwise
disp("unknown!");
disp("unknown!");
endswitch</lang>
endswitch</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 4,820: Line 4,820:
Conditional structures are :
Conditional structures are :


<lang Oforth>aBoolean ifTrue: [ ...]
<syntaxhighlight lang="oforth">aBoolean ifTrue: [ ...]
aBoolean ifFalse: [ ... ]
aBoolean ifFalse: [ ... ]
aObject ifNull: [ ... ]
aObject ifNull: [ ... ]
aObject ifNotNull: [ ... ]
aObject ifNotNull: [ ... ]
aObject ifZero: [ ... ]</lang>
aObject ifZero: [ ... ]</syntaxhighlight>


Each conditional structure consume the object on the top of the stack.
Each conditional structure consume the object on the top of the stack.
Each conditional structure can be followed by a else block
Each conditional structure can be followed by a else block
<lang Oforth>else: [ ... ]</lang>
<syntaxhighlight lang="oforth">else: [ ... ]</syntaxhighlight>


Example :
Example :


<lang Oforth>Number virtual: sgn
<syntaxhighlight lang="oforth">Number virtual: sgn
self isPositive
self isPositive
ifTrue: [ self ==0 ifTrue: [ 0 ] else: [ 1 ] ]
ifTrue: [ self ==0 ifTrue: [ 0 ] else: [ 1 ] ]
else: [ -1 ] ;</lang>
else: [ -1 ] ;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
if-then, the simplest conditional primitive.
if-then, the simplest conditional primitive.
<lang scheme>
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4) (print "if-then: equal"))
(if (= (* 2 2) 4) (print "if-then: equal"))
(if (= (* 2 2) 6) (print "if-then: non equal"))
(if (= (* 2 2) 6) (print "if-then: non equal"))
; ==> if-then: equal
; ==> if-then: equal
</syntaxhighlight>
</lang>


if-then-else, the full conditional 'if' primitive.
if-then-else, the full conditional 'if' primitive.
<lang scheme>
<syntaxhighlight lang="scheme">
(if (= (* 2 2) 4) (print "if-then-else: equal") (print "if-then-else: non equal"))
(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"))
(if (= (* 2 2) 6) (print "if-then-else: non equal") (print "if-then-else: i don't know"))
; ==> if-then-else: equal
; ==> if-then-else: equal
; ==> if-then-else: i don't know
; ==> if-then-else: i don't know
</syntaxhighlight>
</lang>


unless, the opposite for 'if'.
unless, the opposite for 'if'.
<lang scheme>
<syntaxhighlight lang="scheme">
(unless (= (* 2 2) 4) (print "unless: non equal"))
(unless (= (* 2 2) 4) (print "unless: non equal"))
(unless (= (* 2 2) 6) (print "unless: i don't know"))
(unless (= (* 2 2) 6) (print "unless: i don't know"))
Line 4,863: Line 4,863:
; ==> unless: equal
; ==> unless: equal
; ==> unless: i don't know
; ==> unless: i don't know
</syntaxhighlight>
</lang>


case, the sequence of comparing values.
case, the sequence of comparing values.
<lang scheme>
<syntaxhighlight lang="scheme">
(case (* 2 2)
(case (* 2 2)
(3
(3
Line 4,877: Line 4,877:
(print "case: i don't know")))
(print "case: i don't know")))
; ==> case: 4
; ==> case: 4
</syntaxhighlight>
</lang>


additionally, case can select vectors with variables filling
additionally, case can select vectors with variables filling
<lang scheme>
<syntaxhighlight lang="scheme">
(case (vector 'selector 1 2 3)
(case (vector 'selector 1 2 3)
(['case1 x y]
(['case1 x y]
Line 4,889: Line 4,889:
(print "case: i don't know")))
(print "case: i don't know")))
; ==> tuple-case: selector 1, 2, 3
; ==> tuple-case: selector 1, 2, 3
</syntaxhighlight>
</lang>


cond, the sequnce of comparators.
cond, the sequnce of comparators.
<lang scheme>
<syntaxhighlight lang="scheme">
(cond
(cond
((= (* 2 2) 4)
((= (* 2 2) 4)
Line 4,901: Line 4,901:
(print "cond: i don't know")))
(print "cond: i don't know")))
; ==> cond: equal
; ==> cond: equal
</syntaxhighlight>
</lang>


case-lambda, selecting the lambda based on arguments count.
case-lambda, selecting the lambda based on arguments count.
<lang scheme>
<syntaxhighlight lang="scheme">
(define smart (case-lambda
(define smart (case-lambda
((x)
((x)
Line 4,915: Line 4,915:
(smart 1 2) ; ==> 1, 2, -
(smart 1 2) ; ==> 1, 2, -
(smart 1 2 3) ; ==> 1, 2, 3
(smart 1 2 3) ; ==> 1, 2, 3
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
Line 4,924: Line 4,924:
may also be a list of conditional expressions separated by commas. The expressions are evaluated left-to-right, and evaluation
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,
will stop with the first '0' result. For example,
<lang ooRexx>if arg~isa(.string) & arg~left(1) == "*" then call processArg arg</lang>
<syntaxhighlight lang="oorexx">if arg~isa(.string) & arg~left(1) == "*" then call processArg arg</syntaxhighlight>


would fail with a syntax error if the variable arg does not hold a string because the right-hand-side of the expression
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
is still evaluated. This can be coded as


<lang ooRexx>if arg~isa(.string), arg~left(1) == "*" then call processArg arg</lang>
<syntaxhighlight lang="oorexx">if arg~isa(.string), arg~left(1) == "*" then call processArg arg</syntaxhighlight>
With this form, the second conditional expression is only evaluated if the first expression is true.
With this form, the second conditional expression is only evaluated if the first expression is true.


===IF THEN --- IF THEN/ELSE===
===IF THEN --- IF THEN/ELSE===
<syntaxhighlight lang="oorexx">
<lang ooRexx>
if y then x=6 /* Y must be either 0 or 1 */
if y then x=6 /* Y must be either 0 or 1 */


Line 4,959: Line 4,959:
else nop
else nop
else if z<0 then z=-y
else if z<0 then z=-y
</syntaxhighlight>
</lang>


===SELECT WHEN===
===SELECT WHEN===
<syntaxhighlight lang="oorexx">
<lang ooRexx>
/*the WHEN conditional operators are the same as */
/*the WHEN conditional operators are the same as */
/*the IF conditional operators. */
/*the IF conditional operators. */
Line 4,977: Line 4,977:
/*were satisfiied, a SYNTAX condition is raised (error).*/
/*were satisfiied, a SYNTAX condition is raised (error).*/
end
end
</syntaxhighlight>
</lang>
===SELECT WHEN/OTHERWISE===
===SELECT WHEN/OTHERWISE===
<syntaxhighlight lang="oorexx">
<lang ooRexx>
select
select
when a=='angel' then many='host'
when a=='angel' then many='host'
Line 4,994: Line 4,994:
exit 13
exit 13
end
end
</syntaxhighlight>
</lang>


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
if a then b=c else b=d
if a then b=c else b=d


Line 5,019: Line 5,019:
end select
end select


</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
===if-then-else===
===if-then-else===
<lang oz>proc {PrintParity X}
<syntaxhighlight lang="oz">proc {PrintParity X}
if {IsEven X} then
if {IsEven X} then
{Show even}
{Show even}
Line 5,031: Line 5,031:
{Show 'should not happen'}
{Show 'should not happen'}
end
end
end</lang>
end</syntaxhighlight>


===if-then-else as a ternary operator===
===if-then-else as a ternary operator===
<lang oz>fun {Max X Y}
<syntaxhighlight lang="oz">fun {Max X Y}
if X > Y then X else Y end
if X > Y then X else Y end
end</lang>
end</syntaxhighlight>


===case statement===
===case statement===
<lang oz>fun {Fac X}
<syntaxhighlight lang="oz">fun {Fac X}
case X of 0 then 1
case X of 0 then 1
[] _ then X * {Fac X-1}
[] _ then X * {Fac X-1}
end
end
end</lang>
end</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
GP uses a simple <code>if</code> statement:
GP uses a simple <code>if</code> statement:
<lang parigp>if(condition, do_if_true, do_if_false)</lang>
<syntaxhighlight lang="parigp">if(condition, do_if_true, do_if_false)</syntaxhighlight>
and short-circuit <code>&&</code> and <code>||</code> (which can be abbreviated <code>&</code> and <code>|</code> if desired).
and short-circuit <code>&&</code> and <code>||</code> (which can be abbreviated <code>&</code> and <code>|</code> if desired).


Line 5,055: Line 5,055:
===if-then-else===
===if-then-else===


<lang pascal>IF condition1 THEN
<syntaxhighlight lang="pascal">IF condition1 THEN
procedure1
procedure1
ELSE
ELSE
Line 5,077: Line 5,077:
procedure3;
procedure3;
procedure4
procedure4
END;</lang>
END;</syntaxhighlight>


=== case ===
=== case ===
Line 5,086: Line 5,086:
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.
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.


<lang pascal>case i of
<syntaxhighlight lang="pascal">case i of
1,4,9: { executed if i is 1, 4 or 9 }
1,4,9: { executed if i is 1, 4 or 9 }
DoSomething;
DoSomething;
Line 5,095: Line 5,095:
else
else
DoYetAnotherThing;
DoYetAnotherThing;
end;</lang>
end;</syntaxhighlight>


Given the variable "X" as a char the following is valid:
Given the variable "X" as a char the following is valid:


<lang pascal>Case X of
<syntaxhighlight lang="pascal">Case X of
'A' : statement ;
'A' : statement ;
'B' : statement ;
'B' : statement ;
Line 5,105: Line 5,105:
else
else
Statement ;
Statement ;
end;</lang>
end;</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Line 5,112: Line 5,112:
===if/else===
===if/else===


<lang perl>if ($expression) {
<syntaxhighlight lang="perl">if ($expression) {
do_something;
do_something;
}</lang>
}</syntaxhighlight>


<lang perl># postfix conditional
<syntaxhighlight lang="perl"># postfix conditional
do_something if $expression;</lang>
do_something if $expression;</syntaxhighlight>


<lang perl>if ($expression) {
<syntaxhighlight lang="perl">if ($expression) {
do_something;
do_something;
}
}
else {
else {
do_fallback;
do_fallback;
}</lang>
}</syntaxhighlight>


<lang perl>if ($expression1) {
<syntaxhighlight lang="perl">if ($expression1) {
do_something;
do_something;
}
}
Line 5,134: Line 5,134:
else {
else {
do_fallback;
do_fallback;
}</lang>
}</syntaxhighlight>


===unless===
===unless===
Line 5,146: Line 5,146:
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.
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.


<lang perl>$variable = $expression ? $value_for_true : $value_for_false;</lang>
<syntaxhighlight lang="perl">$variable = $expression ? $value_for_true : $value_for_false;</syntaxhighlight>


===logical operators===
===logical operators===


<lang perl>$condition and do_something; # equivalent to $condition ? do_something : $condition</lang>
<syntaxhighlight lang="perl">$condition and do_something; # equivalent to $condition ? do_something : $condition</syntaxhighlight>


<lang perl>$condition or do_something; # equivalent to $condition ? $condition : do_something</lang>
<syntaxhighlight lang="perl">$condition or do_something; # equivalent to $condition ? $condition : do_something</syntaxhighlight>


<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.
<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,162: Line 5,162:
{{works with|Perl|5.10}}
{{works with|Perl|5.10}}


<lang perl>use feature "switch";
<syntaxhighlight lang="perl">use feature "switch";
given ($input) {
given ($input) {
when (0) { print 'input == 0'; }
when (0) { print 'input == 0'; }
Line 5,169: Line 5,169:
when (/rats/) { print 'input matches rats'; }
when (/rats/) { print 'input matches rats'; }
default { do_fallback; }
default { do_fallback; }
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
===if===
===if===
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_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: #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>
Line 5,185: Line 5,185:
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


There is no limit to the number of elsif clauses, including 0. The else clause is also optional,
There is no limit to the number of elsif clauses, including 0. The else clause is also optional,
Line 5,192: Line 5,192:


===iff===
===iff===
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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;">)
<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;">)
<!--</lang>-->
<!--</syntaxhighlight>-->


In an iff() expression, only one of true_expr or false_expr will be evaluated, not both.
In an iff() expression, only one of true_expr or false_expr will be evaluated, not both.
Line 5,202: Line 5,202:
first if statement, and in the second the conditions are evaluated at compile-time and code is only
first if statement, and in the second the conditions are evaluated at compile-time and code is only
emitted for one of the branches.
emitted for one of the branches.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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;">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>
<span style="color: #008080;">if</span> <span style="color: #000000;">DEBUG</span> <span style="color: #008080;">then</span>
Line 5,212: Line 5,212:
<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: #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
<span style="color: #008080;">end</span> <span style="color: #008080;">if
<!--</lang>-->
<!--</syntaxhighlight>-->


===switch===
===switch===
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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;">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>
<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,228: Line 5,228:
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch
<span style="color: #008080;">end</span> <span style="color: #008080;">switch
<!--</lang>-->
<!--</syntaxhighlight>-->


By default there is no fallthough on switch clauses, however you can add(/uncomment) a directive, and you can
By default there is no fallthough on switch clauses, however you can add(/uncomment) a directive, and you can
Line 5,244: Line 5,244:
use them, also have some conditional guards for cross-platform support
use them, also have some conditional guards for cross-platform support


<lang Phix>without js -- (but maybe, at some point, and obviously that is as custom verbatim JavaScript code instead of assembly code)
<syntaxhighlight lang="phix">without js -- (but maybe, at some point, and obviously that is as custom verbatim JavaScript code instead of assembly code)
#ilASM{
#ilASM{
[32]
[32]
Line 5,266: Line 5,266:
syscall
syscall
[]
[]
}</lang>
}</syntaxhighlight>


=={{header|PHL}}==
=={{header|PHL}}==
Line 5,272: Line 5,272:
If-else:
If-else:


<lang phl>var a = 5;
<syntaxhighlight lang="phl">var a = 5;
if (a == 5) {
if (a == 5) {
doSomething();
doSomething();
Line 5,279: Line 5,279:
} else {
} else {
error();
error();
}</lang>
}</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
Line 5,287: Line 5,287:
'''Interpreter''': [[PHP]] 3.x, 4.x, 5.x
'''Interpreter''': [[PHP]] 3.x, 4.x, 5.x


<lang php><?php
<syntaxhighlight lang="php"><?php


$foo = 3;
$foo = 3;
Line 5,308: Line 5,308:
}
}


?></lang>
?></syntaxhighlight>


===switch===
===switch===
Line 5,314: Line 5,314:
'''Interpreter''': [[PHP]] 3.x & 4.x & 5.x
'''Interpreter''': [[PHP]] 3.x & 4.x & 5.x


<lang php><?php
<syntaxhighlight lang="php"><?php


switch ($i)
switch ($i)
Line 5,331: Line 5,331:
}
}


?></lang>
?></syntaxhighlight>


===See Also===
===See Also===
Line 5,348: Line 5,348:
Here are examples of each of these constructs.
Here are examples of each of these constructs.


<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
N = 10,
N = 10,


Line 5,393: Line 5,393:
% condition in function head
% condition in function head
test_func(N) = "less than 14", N < 14 => true.
test_func(N) = "less than 14", N < 14 => true.
test_func(_N) = "not less than 14" => true. </lang>
test_func(_N) = "not less than 14" => true. </syntaxhighlight>


{{out}}
{{out}}
Line 5,405: Line 5,405:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
===Two-way conditions===
===Two-way conditions===
<lang PicoLisp>(if (condition) # If the condition evaluates to non-NIL
<syntaxhighlight lang="picolisp">(if (condition) # If the condition evaluates to non-NIL
(then-do-this) # Then execute the following expression
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(else-do-that) # Else execute all other expressions
Line 5,413: Line 5,413:
(then-do-this) # Then execute the following expression
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(else-do-that) # Else execute all other expressions
(and-more) )</lang>
(and-more) )</syntaxhighlight>
One-way conditions
One-way conditions
<lang PicoLisp>(when (condition) # If the condition evaluates to non-NIL
<syntaxhighlight lang="picolisp">(when (condition) # If the condition evaluates to non-NIL
(then-do-this) # Then execute tall following expressions
(then-do-this) # Then execute tall following expressions
(and-more) )
(and-more) )
Line 5,421: Line 5,421:
(unless (condition) # If the condition evaluates to NIL
(unless (condition) # If the condition evaluates to NIL
(then-do-this) # Then execute all following expressions
(then-do-this) # Then execute all following expressions
(and-more) )</lang>
(and-more) )</syntaxhighlight>
===Four-way condition===
===Four-way condition===
<lang PicoLisp>(if2 (condition1) (condition2) # If both conditions evaluate to non-NIL
<syntaxhighlight lang="picolisp">(if2 (condition1) (condition2) # If both conditions evaluate to non-NIL
(expression-both) # Then execute this expression
(expression-both) # Then execute this expression
(expression-first) # Otherwise this for the first
(expression-first) # Otherwise this for the first
(expression-second) # or this the second condition.
(expression-second) # or this the second condition.
(expression-none) # If both are NIL, all following expressions
(expression-none) # If both are NIL, all following expressions
(and-more) )</lang>
(and-more) )</syntaxhighlight>
===Multiple conditions===
===Multiple conditions===
<lang PicoLisp>(cond
<syntaxhighlight lang="picolisp">(cond
((condition1) # If this condition evaluates to non-NIL
((condition1) # If this condition evaluates to non-NIL
(expression 1) # Execute these expression(s)
(expression 1) # Execute these expression(s)
Line 5,450: Line 5,450:
(NIL # If none evaluated to NIL
(NIL # If none evaluated to NIL
(expression 1) # Execute these expression(s)
(expression 1) # Execute these expression(s)
(more 1) )</lang>
(more 1) )</syntaxhighlight>


===Selection===
===Selection===
<lang PicoLisp>(case (expression) # Evaluate the expression
<syntaxhighlight lang="picolisp">(case (expression) # Evaluate the expression
(value1 # If it is equal to, or member of, 'value1'
(value1 # If it is equal to, or member of, 'value1'
(do-this1) # Execute these expression(s)
(do-this1) # Execute these expression(s)
Line 5,461: Line 5,461:
(do-that2) )
(do-that2) )
(T # Else execute final expression(s)
(T # Else execute final expression(s)
(do-something-else) ) )</lang>
(do-something-else) ) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
===if-then-else===
===if-then-else===
<lang pli>if condition_exp then unique_statement; else unique_statement;
<syntaxhighlight lang="pli">if condition_exp then unique_statement; else unique_statement;


if condition_exp then
if condition_exp then
Line 5,478: Line 5,478:
else do;
else do;
list_of_statements;
list_of_statements;
end;</lang>
end;</syntaxhighlight>


So a cascading form can be derived from:
So a cascading form can be derived from:
<lang pli>if condition_exp1 then
<syntaxhighlight lang="pli">if condition_exp1 then
statement_1;
statement_1;
else if condition_exp2 then
else if condition_exp2 then
Line 5,501: Line 5,501:
else do;
else do;
list_of_statements;
list_of_statements;
end;</lang>
end;</syntaxhighlight>


=== case ===
=== case ===
Line 5,507: Line 5,507:


==== select - format 1 ====
==== select - format 1 ====
<lang pli>select (i); /* select on value of variable */
<syntaxhighlight lang="pli">select (i); /* select on value of variable */
when (1,4,9)
when (1,4,9)
do;
do;
Line 5,522: Line 5,522:
statement_s;
statement_s;
end;
end;
end;</lang>
end;</syntaxhighlight>


==== select - format 2 ====
==== select - format 2 ====
<lang pli>select; /* select first matching condition */
<syntaxhighlight lang="pli">select; /* select first matching condition */
when (i = 4)
when (i = 4)
do;
do;
Line 5,545: Line 5,545:
statement_s;
statement_s;
end;
end;
end;</lang>
end;</syntaxhighlight>


Notes:
Notes:
Line 5,555: Line 5,555:
=={{header|PL/M}}==
=={{header|PL/M}}==
IF-THEN-ELSE:
IF-THEN-ELSE:
<lang pli>/* IF-THEN-ELSE - THE ELSE STATEMENT; PART IS OPTIONAL */
<syntaxhighlight lang="pli">/* IF-THEN-ELSE - THE ELSE STATEMENT; PART IS OPTIONAL */
IF COND THEN STATEMENT1; ELSE STATEMENT2;
IF COND THEN STATEMENT1; ELSE STATEMENT2;


Line 5,562: Line 5,562:
ELSE IF CONB2 THEN STATEMENT2;
ELSE IF CONB2 THEN STATEMENT2;
ELSE IF CONB3 THEN STATEMENT3;
ELSE IF CONB3 THEN STATEMENT3;
ELSE STATEMENTX;</lang>
ELSE STATEMENTX;</syntaxhighlight>


DO-CASE:
DO-CASE:
<lang pli>/* CASE STATEMENT - EXECUTES STATEMENT0, STATEMENT1, ETC. */
<syntaxhighlight lang="pli">/* CASE STATEMENT - EXECUTES STATEMENT0, STATEMENT1, ETC. */
/* DEPENDING ON WHETHER EXPR EVALUATES TO 0, 1, ... */
/* DEPENDING ON WHETHER EXPR EVALUATES TO 0, 1, ... */
/* EXPR MUST BE IN RANGE OR THE PROGRAM WILL JUMP TO HYPERSPACE */
/* EXPR MUST BE IN RANGE OR THE PROGRAM WILL JUMP TO HYPERSPACE */
Line 5,572: Line 5,572:
STATEMENT1;
STATEMENT1;
...
...
END;</lang>
END;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 5,578: Line 5,578:
The simplest conditional is:
The simplest conditional is:


<lang pop11>if condition then
<syntaxhighlight lang="pop11">if condition then
;;; Action
;;; Action
endif;</lang>
endif;</syntaxhighlight>


Two way conditional looks like:
Two way conditional looks like:


<lang pop11>if condition then
<syntaxhighlight lang="pop11">if condition then
;;; Action1
;;; Action1
else
else
;;; Alternative action
;;; Alternative action
endif;</lang>
endif;</syntaxhighlight>


One can do multiway choice using elseif clause
One can do multiway choice using elseif clause


<lang pop11>if condition1 then
<syntaxhighlight lang="pop11">if condition1 then
;;; Action1
;;; Action1
elseif condition2 then
elseif condition2 then
Line 5,602: Line 5,602:
else
else
;;; Alternative action
;;; Alternative action
endif;</lang>
endif;</syntaxhighlight>


Instead of if keyword one can use unless keyword.
Instead of if keyword one can use unless keyword.


<lang pop11>unless condition then /* Action */ endunless;</lang>
<syntaxhighlight lang="pop11">unless condition then /* Action */ endunless;</syntaxhighlight>


has the same meaning as
has the same meaning as


<lang pop11>if not(condition) then /* Action */ endif;</lang>
<syntaxhighlight lang="pop11">if not(condition) then /* Action */ endif;</syntaxhighlight>


One can also use elseunless keword.
One can also use elseunless keword.


<lang pop11>if condition1 then
<syntaxhighlight lang="pop11">if condition1 then
;;; Action1
;;; Action1
elseunless condition2 then
elseunless condition2 then
Line 5,620: Line 5,620:
endif;
endif;
;;; Action2
;;; Action2
endif;</lang>
endif;</syntaxhighlight>


has the same meaning as
has the same meaning as


<lang pop11>if condition1 then
<syntaxhighlight lang="pop11">if condition1 then
;;; Action1
;;; Action1
elseif not(condition2) then
elseif not(condition2) then
;;; Action2
;;; Action2
endif;</lang>
endif;</syntaxhighlight>


Note that conditional must end in matching keyword, if must be finished by endif, unless must be finished by endunless (in the
Note that conditional must end in matching keyword, if must be finished by endif, unless must be finished by endunless (in the
Line 5,635: Line 5,635:
Pop11 conditional is an expression:
Pop11 conditional is an expression:


<lang pop11>if x > 0 then 1 elseif x < 0 then -1 else 0 endif -> sign_x ;</lang>
<syntaxhighlight lang="pop11">if x > 0 then 1 elseif x < 0 then -1 else 0 endif -> sign_x ;</syntaxhighlight>


assigns sign of x to sign_x.
assigns sign of x to sign_x.
Line 5,641: Line 5,641:
Instead of multiway if one can use switchon construct (which is equivalent to a special case of if, but may be shorter).
Instead of multiway if one can use switchon construct (which is equivalent to a special case of if, but may be shorter).


<lang pop11>switchon(x)
<syntaxhighlight lang="pop11">switchon(x)
case .isstring then printf('A1');
case .isstring then printf('A1');
notcase .isinteger then printf('A2');
notcase .isinteger then printf('A2');
Line 5,647: Line 5,647:
case > 4 andcase < 15 then printf('A4');
case > 4 andcase < 15 then printf('A4');
else printf('A5');
else printf('A5');
endswitchon;</lang>
endswitchon;</syntaxhighlight>


There is also multiway goto statement and conditional control transfers, we explain them together with other control transfers
There is also multiway goto statement and conditional control transfers, we explain them together with other control transfers
Line 5,654: Line 5,654:
Pop11 also has preprocessor allowing conditional compilation:
Pop11 also has preprocessor allowing conditional compilation:


<lang pop11>#_IF condition1
<syntaxhighlight lang="pop11">#_IF condition1
/* Variant 1 */
/* Variant 1 */
#_ELSEIF condition2
#_ELSEIF condition2
Line 5,660: Line 5,660:
#_ELSE
#_ELSE
/* Variant 3 */
/* Variant 3 */
#_ENDIF</lang>
#_ENDIF</syntaxhighlight>


condition1 and condition2 are arbitrary Pop11 expressions (they have access to all previously compiled code).
condition1 and condition2 are arbitrary Pop11 expressions (they have access to all previously compiled code).
Line 5,670: Line 5,670:
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):
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):


<lang postscript>9 10 lt {(9 is less than 10) show} if</lang>
<syntaxhighlight lang="postscript">9 10 lt {(9 is less than 10) show} if</syntaxhighlight>


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:
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:


<lang postscript>/a 5 lt {(yeah)} {(nope)} ifelse show</lang>
<syntaxhighlight lang="postscript">/a 5 lt {(yeah)} {(nope)} ifelse show</syntaxhighlight>


will render either the string "yeah" or "nope" depending on whether <tt>a</tt> is less than 5 or not.
will render either the string "yeah" or "nope" depending on whether <tt>a</tt> is less than 5 or not.
Line 5,680: Line 5,680:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
===If, ElseIf, Else===
===If, ElseIf, Else===
<lang powershell># standard if
<syntaxhighlight lang="powershell"># standard if
if (condition) {
if (condition) {
# ...
# ...
Line 5,699: Line 5,699:
} else {
} else {
# ...
# ...
}</lang>
}</syntaxhighlight>
===Switch===
===Switch===
<lang powershell># standard switch
<syntaxhighlight lang="powershell"># standard switch
switch ($var) {
switch ($var) {
1 { "Value was 1" }
1 { "Value was 1" }
Line 5,730: Line 5,730:
"\d+" { "Line started with a number" }
"\d+" { "Line started with a number" }
"\s+" { "Line started with whitespace" }
"\s+" { "Line started with whitespace" }
}</lang>
}</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 5,736: Line 5,736:
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:
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:


<lang Prolog>go :- write('Hello, World!'), nl.</lang>
<syntaxhighlight lang="prolog">go :- write('Hello, World!'), nl.</syntaxhighlight>


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.)
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.)


<lang Prolog>fact(foo).
<syntaxhighlight lang="prolog">fact(foo).
fact(bar).
fact(bar).
fact(baz).
fact(baz).


go :- fact(booger).
go :- fact(booger).
go :- fact(bar).</lang>
go :- fact(bar).</syntaxhighlight>


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.
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.


<lang Prolog>fact(X) :-
<syntaxhighlight lang="prolog">fact(X) :-
( X = foo
( X = foo
; X = bar
; X = bar
Line 5,756: Line 5,756:
go :-
go :-
( fact(booger)
( fact(booger)
; fact(bar) ).</lang>
; fact(bar) ).</syntaxhighlight>


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.
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,762: Line 5,762:
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):
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):


<lang Prolog>fact(X) :-
<syntaxhighlight lang="prolog">fact(X) :-
( X = bar -> write('You got me!'), nl
( X = bar -> write('You got me!'), nl
; write(X), write(' is not right!'), nl, fail ).
; write(X), write(' is not right!'), nl, fail ).
Line 5,768: Line 5,768:
go :-
go :-
( fact(booger)
( fact(booger)
; fact(bar) ).</lang>
; fact(bar) ).</syntaxhighlight>


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.
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,775: Line 5,775:
{{works with|PureBasic|4.41}}
{{works with|PureBasic|4.41}}
===If, Elseif, Else===
===If, Elseif, Else===
<lang PureBasic>If a = 0
<syntaxhighlight lang="purebasic">If a = 0
Debug "a = 0"
Debug "a = 0"


Line 5,784: Line 5,784:
Debug "a < 0"
Debug "a < 0"


EndIf</lang>
EndIf</syntaxhighlight>


===Select===
===Select===
<lang PureBasic>Variable = 2
<syntaxhighlight lang="purebasic">Variable = 2


Select Variable
Select Variable
Line 5,801: Line 5,801:
Default
Default
Debug "Variable = something else..."
Debug "Variable = something else..."
EndSelect</lang>
EndSelect</syntaxhighlight>


===CompilerIf===
===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.
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
CompilerIf #PB_Compiler_OS = #PB_OS_Linux And #PB_Compiler_Processor = #PB_Processor_x86
Debug "Compiled on x86 Linux"
Debug "Compiled on x86 Linux"
Line 5,811: Line 5,811:
Debug "Compiled on something else"
Debug "Compiled on something else"
CompilerEndIf
CompilerEndIf
</syntaxhighlight>
</lang>


===CompilerSelect===
===CompilerSelect===
<syntaxhighlight lang="purebasic">
<lang PureBasic>
CompilerSelect #PB_Compiler_OS
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_Linux
CompilerCase #PB_OS_Linux
Line 5,825: Line 5,825:
Debug "Compiled on something else"
Debug "Compiled on something else"
CompilerEndIf
CompilerEndIf
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
===if-then-else===
===if-then-else===


<lang python>if x == 0:
<syntaxhighlight lang="python">if x == 0:
foo()
foo()
elif x == 1:
elif x == 1:
Line 5,837: Line 5,837:
baz()
baz()
else:
else:
boz()</lang>
boz()</syntaxhighlight>


===ternary expressions===
===ternary expressions===
'''Interpreter:''' [[Python]] 2.5
'''Interpreter:''' [[Python]] 2.5


<lang python>true_value if condition else false_value</lang>
<syntaxhighlight lang="python">true_value if condition else false_value</syntaxhighlight>


Example:
Example:
<lang python>>>> secret='foo'
<syntaxhighlight lang="python">>>> secret='foo'
>>> print 'got it' if secret=='foo' else 'try again'
>>> print 'got it' if secret=='foo' else 'try again'
'got it'</lang>
'got it'</syntaxhighlight>


'''Note:''' this syntax is valid as an expression, the clauses cannot constain statements. The foregoing example is equivalent to:
'''Note:''' this syntax is valid as an expression, the clauses cannot constain statements. The foregoing example is equivalent to:


<lang python>>>> secret = 'foo'
<syntaxhighlight lang="python">>>> secret = 'foo'
>>> result = 'got it' if secret=='foo' else 'try again'
>>> result = 'got it' if secret=='foo' else 'try again'
>>> print result
>>> print result
'got it'</lang>
'got it'</syntaxhighlight>


===Function dispatch dictionary===
===Function dispatch dictionary===
Line 5,860: Line 5,860:
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.
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.


<lang python>dispatcher = dict()
<syntaxhighlight lang="python">dispatcher = dict()
dispatcher[0]=foo # Not foo(): we bind the dictionary entry to the function's object,
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
# NOT to the results returned by an invocation of the function
Line 5,870: Line 5,870:
# or with no "default" case:
# or with no "default" case:
if x in dispatcher:
if x in dispatcher:
results=dispatcher[x]()</lang>
results=dispatcher[x]()</syntaxhighlight>


<lang python># The above, but with a dict literal
<syntaxhighlight lang="python"># The above, but with a dict literal
dispatcher = {
dispatcher = {
0: foo,
0: foo,
Line 5,879: Line 5,879:
}
}
# ...
# ...
results = dispatcher.get(x, boz)()</lang>
results = dispatcher.get(x, boz)()</syntaxhighlight>


<lang python># Or without the temp variable
<syntaxhighlight lang="python"># Or without the temp variable
# (it's up to the reader to decide how "pythonic" this is or isn't)
# (it's up to the reader to decide how "pythonic" this is or isn't)
results = {
results = {
Line 5,887: Line 5,887:
1: bar,
1: bar,
2: baz,
2: baz,
}.get(x, boz)()</lang>
}.get(x, boz)()</syntaxhighlight>


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.
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.
Line 5,894: Line 5,894:


=={{header|QB64}}==
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>


Print "QB64/Qbasic conditional structures"
Print "QB64/Qbasic conditional structures"
Line 6,021: Line 6,021:


End Sub
End Sub
</syntaxhighlight>
</lang>




Line 6,097: Line 6,097:
===if===
===if===
Like most languages, R has an if statement as well as if-then-else:
Like most languages, R has an if statement as well as if-then-else:
<lang rsplus>x <- 0
<syntaxhighlight lang="rsplus">x <- 0
if(x == 0) print("foo")
if(x == 0) print("foo")
x <- 1
x <- 1
if(x == 0) print("foo")
if(x == 0) print("foo")
if(x == 0) print("foo") else print("bar")</lang>
if(x == 0) print("foo") else print("bar")</syntaxhighlight>
{{out}}
{{out}}
<pre>> if(x == 0) print("foo")
<pre>> if(x == 0) print("foo")
Line 6,111: Line 6,111:
===switch===
===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.
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.
<lang rsplus>x <- 2
<syntaxhighlight lang="rsplus">x <- 2
switch(x, print("Print if x == 1"), print("Print if x == 2"))</lang>
switch(x, print("Print if x == 1"), print("Print if x == 2"))</syntaxhighlight>
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.
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.
<lang rsplus>x <- 3
<syntaxhighlight lang="rsplus">x <- 3
switch(x, print("Print if x == 1"), print("Print if x == 2"))
switch(x, print("Print if x == 1"), print("Print if x == 2"))
x <- 2.7
x <- 2.7
switch(x, print("Print if x == 1"), print("Print if x == 2 or if there is rounding to 2"))</lang>
switch(x, print("Print if x == 1"), print("Print if x == 2 or if there is rounding to 2"))</syntaxhighlight>
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.
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.
<lang rsplus>x <- "match"
<syntaxhighlight lang="rsplus">x <- "match"
switch(x, mat = 0, match = 10, other = 100, 1000)
switch(x, mat = 0, match = 10, other = 100, 1000)
x <- "ma"
x <- "ma"
switch(x, mat = 0, match = 10, other = 100, 1000)
switch(x, mat = 0, match = 10, other = 100, 1000)
x <- "foo"
x <- "foo"
switch(x, mat = 0, match = 10, other = 100, 1000)</lang>
switch(x, mat = 0, match = 10, other = 100, 1000)</syntaxhighlight>
{{out}}
{{out}}
<pre>> switch(x, print("Print if x == 1"), print("Print if x == 2"))
<pre>> switch(x, print("Print if x == 1"), print("Print if x == 2"))
Line 6,145: Line 6,145:


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:
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:
<lang rsplus>data <- c(1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0)
<syntaxhighlight 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")</lang>
ifelse(data == 1, "Yes", "No")</syntaxhighlight>
{{out}}
{{out}}
<pre>> ifelse(data == 1, "Yes", "No")
<pre>> ifelse(data == 1, "Yes", "No")
Line 6,155: Line 6,155:
===[http://docs.racket-lang.org/reference/if.html#%28form._%28%28quote._~23~25kernel%29._if%29%29 if]===
===[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
If-expressions in Racket must have both branches
<lang racket>
<syntaxhighlight lang="racket">
(if (< x 10)
(if (< x 10)
"small"
"small"
"big")
"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]===
===[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
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
<lang racket>
<syntaxhighlight lang="racket">
(when (< x 10)
(when (< x 10)
(define y (* x 10))
(define y (* x 10))
(printf "small\n"))
(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]===
===[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:
Used for multiple conditions:
<lang racket>
<syntaxhighlight lang="racket">
(printf "x is ~a\n"
(printf "x is ~a\n"
(cond [(< x 1) "tiny"]
(cond [(< x 1) "tiny"]
Line 6,179: Line 6,179:
[(< x 100000000) "huge"]
[(< x 100000000) "huge"]
[else "gigantic"]))
[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]===
===[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
Similar to a "switch" statement in other languages
<lang racket>
<syntaxhighlight lang="racket">
(case x
(case x
[(1) "one"]
[(1) "one"]
Line 6,192: Line 6,192:
[(5 7 9) "odd"]
[(5 7 9) "odd"]
[else "something else"])
[else "something else"])
</syntaxhighlight>
</lang>


===etc===
===etc===
Line 6,204: Line 6,204:
</li><li> <tt>unless</tt> no longer permits <tt>elsif</tt> or <tt>else</tt> blocks.
</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:
</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:
<lang perl6>if won() -> $prize {
<syntaxhighlight lang="raku" line>if won() -> $prize {
say "You won $prize.";
say "You won $prize.";
}</lang>
}</syntaxhighlight>
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>
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===
===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:
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:
<lang perl6>given lc prompt("Done? ") {
<syntaxhighlight lang="raku" line>given lc prompt("Done? ") {
when 'yes' { return }
when 'yes' { return }
when 'no' { next }
when 'no' { next }
default { say "Please answer either yes or no." }
default { say "Please answer either yes or no." }
}</lang>
}</syntaxhighlight>
<tt>when</tt> blocks are allowed in any block that topicalizes <tt>$_</tt>, including a
<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>)
<tt>for</tt> loop (assuming one of its loop variables is bound to <tt>$_</tt>)
Line 6,223: Line 6,223:
===Ternary operator===
===Ternary operator===
The [[wp:ternary operator|ternary operator]] looks like this:
The [[wp:ternary operator|ternary operator]] looks like this:
<lang perl6>$expression ?? do_something !! do_fallback</lang>
<syntaxhighlight lang="raku" line>$expression ?? do_something !! do_fallback</syntaxhighlight>


===Other short-circuiting operators===
===Other short-circuiting operators===
Line 6,231: Line 6,231:
===If-Either-Case-Switch===
===If-Either-Case-Switch===
If the result is true, the block! will be evaluated. If false nothing happens.
If the result is true, the block! will be evaluated. If false nothing happens.
<lang Red>>> if 10 > 2 [print "ten is bigger"]
<syntaxhighlight lang="red">>> if 10 > 2 [print "ten is bigger"]
ten is bigger</lang>
ten is bigger</syntaxhighlight>
===EITHER===
===EITHER===
If the result is true the first block! will be evaluated.
If the result is true the first block! will be evaluated.
If false the second block! will be evaluated.
If false the second block! will be evaluated.
<lang Red>>> either 3 > 2 [print "Three larger"][print "Nope!"]
<syntaxhighlight lang="red">>> either 3 > 2 [print "Three larger"][print "Nope!"]
Three larger</lang>
Three larger</syntaxhighlight>
===CASE===
===CASE===
The block! following the first true condition is evaluated.
The block! following the first true condition is evaluated.
<lang Red>n: 50
<syntaxhighlight lang="red">n: 50
case [
case [
n < 10 [print "small number"]
n < 10 [print "small number"]
Line 6,261: Line 6,261:
medium number
medium number
large number
large number
none of these</lang>
none of these</syntaxhighlight>


===SWITCH===
===SWITCH===
<lang Red>switch "india" [
<syntaxhighlight lang="red">switch "india" [
"a" [print "string"]
"a" [print "string"]
23 [print "integer"]
23 [print "integer"]
Line 6,280: Line 6,280:
]
]


no match</lang>
no match</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
===choose, if, and -if===
===choose, if, and -if===
<lang Retro>condition [ true statements ] if
<syntaxhighlight lang="retro">condition [ true statements ] if
condition [ false statements ] -if
condition [ false statements ] -if
condition [ true statements ] [ false statements ] choose</lang>
condition [ true statements ] [ false statements ] choose</syntaxhighlight>


These forms can be used interactively, or inside function definitions.
These forms can be used interactively, or inside function definitions.


===when===
===when===
<lang Retro>:foo (n-)
<syntaxhighlight lang="retro">:foo (n-)
#1 [ ( if quote evaluates to true ) ] case
#1 [ ( if quote evaluates to true ) ] case
#2 [ ( if quote evaluates to true ) ] case
#2 [ ( if quote evaluates to true ) ] case
#3 [ ( if quote evaluates to true ) ] case
#3 [ ( if quote evaluates to true ) ] case
drop ( default action ) ;</lang>
drop ( default action ) ;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===IF--THEN, IF--THEN--ELSE===
===IF--THEN, IF--THEN--ELSE===
<lang rexx>if y then @=6 /* Y must be either 0 or 1 */
<syntaxhighlight 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. */
if t**2>u then x=y /*simple IF with THEN & ELSE. */
Line 6,316: Line 6,316:
substr(abc,4,1)=='~' then if z=0 then call punt
substr(abc,4,1)=='~' then if z=0 then call punt
else nop /*NOP pairs up IF*/
else nop /*NOP pairs up IF*/
else if z<0 then z=-y /*alignment helps*/</lang>
else if z<0 then z=-y /*alignment helps*/</syntaxhighlight>


===SELECT--WHEN===
===SELECT--WHEN===
<lang rexx> /*the WHEN conditional operators are the same as*/
<syntaxhighlight lang="rexx"> /*the WHEN conditional operators are the same as*/
/*the IF conditional operators. */
/*the IF conditional operators. */
select
select
Line 6,342: Line 6,342:
when a=='wolf' then many='pack'
when a=='wolf' then many='pack'
otherwise many='?'
otherwise many='?'
end /*2nd select*/ /* [↑] uses OTHERWISE as a catch-all.*/</lang>
end /*2nd select*/ /* [↑] uses OTHERWISE as a catch-all.*/</syntaxhighlight>


===SELECT--WHEN/OTHERWISE===
===SELECT--WHEN/OTHERWISE===
<lang rexx> select
<syntaxhighlight lang="rexx"> select
when g=='angel' then many='host'
when g=='angel' then many='host'
when g=='ass' | g=='donkey' then many='pace'
when g=='ass' | g=='donkey' then many='pace'
Line 6,358: Line 6,358:
say
say
exit 13
exit 13
end /*select*/</lang>
end /*select*/</syntaxhighlight>


=={{header|Rhope}}==
=={{header|Rhope}}==
{{works with|Rhope|alpha 1}}
{{works with|Rhope|alpha 1}}
===if-then-else===
===if-then-else===
<lang rhope>If[cond]
<syntaxhighlight lang="rhope">If[cond]
|:
|:
Do Something[]
Do Something[]
:||:
:||:
Do Something Else[]
Do Something Else[]
:|</lang>
:|</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
'''if-but-else-ok'''
'''if-but-else-ok'''
<lang ring>If x == 1
<syntaxhighlight lang="ring">If x == 1
SomeFunc1()
SomeFunc1()
But x == 2
But x == 2
Line 6,378: Line 6,378:
Else
Else
SomeFunc()
SomeFunc()
Ok</lang>
Ok</syntaxhighlight>


'''Switch'''
'''Switch'''
<lang ring>Switch x
<syntaxhighlight lang="ring">Switch x
On 1
On 1
SomeFunc1()
SomeFunc1()
Line 6,388: Line 6,388:
Other
Other
SomeFunc()
SomeFunc()
Off</lang>
Off</syntaxhighlight>


=={{header|RLaB}}==
=={{header|RLaB}}==
Line 6,394: Line 6,394:
=== if ===
=== if ===
Block of instructions following the ''if'' command has to be always enclosed in curly brackets.
Block of instructions following the ''if'' command has to be always enclosed in curly brackets.
<syntaxhighlight lang="rlab">
<lang RLaB>
if (x==1)
if (x==1)
{
{
// do something
// do something
}
}
</syntaxhighlight>
</lang>


=== if-else ===
=== if-else ===
Line 6,405: Line 6,405:
Consider an example:
Consider an example:


<syntaxhighlight lang="rlab">
<lang RLaB>
if (x==1)
if (x==1)
{
{
Line 6,414: Line 6,414:
y = sin(const.pi*(1-x)) / (1-x);
y = sin(const.pi*(1-x)) / (1-x);
}
}
</syntaxhighlight>
</lang>


<syntaxhighlight lang="rlab">
<lang RLaB>
if (x==1)
if (x==1)
{
{
Line 6,429: Line 6,429:
y = rand();
y = rand();
}}
}}
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 6,435: Line 6,435:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang Runbasic>' Boolean Evaluations
<syntaxhighlight lang="runbasic">' Boolean Evaluations
'
'
' > Greater Than
' > Greater Than
Line 6,514: Line 6,514:
print "color unknown"
print "color unknown"


end select</lang>
end select</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Line 6,520: Line 6,520:
====Conditional compilation====
====Conditional compilation====
Rust supports conditional compilation via the `cfg` annotation.
Rust supports conditional compilation via the `cfg` annotation.
<lang rust>// This function will only be compiled if we are compiling on Linux
<syntaxhighlight lang="rust">// This function will only be compiled if we are compiling on Linux
#[cfg(target_os = "linux")]
#[cfg(target_os = "linux")]
fn running_linux() {
fn running_linux() {
Line 6,541: Line 6,541:
))]
))]
fn highly_specific_function() {}
fn highly_specific_function() {}
</syntaxhighlight>
</lang>
Conditional compilation may also be achieved via the `cfg!` macro.
Conditional compilation may also be achieved via the `cfg!` macro.
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
if cfg!(target_os = "linux") {
if cfg!(target_os = "linux") {
// Do something
// Do something
}
}
}</lang>
}</syntaxhighlight>


====Generics (static dispatch)====
====Generics (static dispatch)====
By default, generics in Rust are monomorphized, so no vtable lookups at runtime are necessary.
By default, generics in Rust are monomorphized, so no vtable lookups at runtime are necessary.
<lang rust>trait PrintType {
<syntaxhighlight lang="rust">trait PrintType {
fn print_type(&self);
fn print_type(&self);
}
}
Line 6,578: Line 6,578:
prints_type_of_args(&'a', &2.0);
prints_type_of_args(&'a', &2.0);
prints_type_of_args(&'a', &'b');
prints_type_of_args(&'a', &'b');
}</lang>
}</syntaxhighlight>


===Runtime===
===Runtime===
====If-statement====
====If-statement====
<lang rust>if some_conditional {
<syntaxhighlight lang="rust">if some_conditional {
do_stuff();
do_stuff();
} else if some_other_conditional {
} else if some_other_conditional {
Line 6,602: Line 6,602:
// Do something with x_coord and y_coord
// Do something with x_coord and y_coord
}
}
}</lang>
}</syntaxhighlight>


====Match statement====
====Match statement====
Match statements are essentially more powerful switch statements
Match statements are essentially more powerful switch statements
<lang rust>fn some_other_function(p: Option<Point>) {
<syntaxhighlight lang="rust">fn some_other_function(p: Option<Point>) {
match p {
match p {
Some(Point { x: 0, y: 0 }) => println!("Point is on origin"),
Some(Point { x: 0, y: 0 }) => println!("Point is on origin"),
Line 6,615: Line 6,615:
None => println!("We didn't get a point"),
None => println!("We didn't get a point"),
}
}
}</lang>
}</syntaxhighlight>


====Generics (dynamic dispatch)====
====Generics (dynamic dispatch)====
Generics may also be accomplished via dynamic dispatch, so the actual code that is run is determined at compile time.
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:
Using the same trait defined in the static dispatch section:
<lang rust>fn prints_args_dynamic(arg1: &PrintType, arg2: &PrintType) {
<syntaxhighlight lang="rust">fn prints_args_dynamic(arg1: &PrintType, arg2: &PrintType) {
arg1.print_type();
arg1.print_type();
arg2.print_type();
arg2.print_type();
Line 6,627: Line 6,627:
prints_args_dynamic(&'a', &2.0);
prints_args_dynamic(&'a', &2.0);
prints_args_dynamic(&6.3,&'c');
prints_args_dynamic(&6.3,&'c');
}</lang>
}</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==


<lang sather> if EXPR then
<syntaxhighlight lang="sather"> if EXPR then
-- CODE
-- CODE
elsif EXPR then
elsif EXPR then
Line 6,637: Line 6,637:
else
else
-- CODE
-- CODE
end;</lang>
end;</syntaxhighlight>


EXPR must evaluate to BOOL (true or false); <code>elsif</code> and <code>else</code> are optional.
EXPR must evaluate to BOOL (true or false); <code>elsif</code> and <code>else</code> are optional.


<lang sather> case EXPR
<syntaxhighlight lang="sather"> case EXPR
when EXPRL then
when EXPRL then
-- CODE
-- CODE
Line 6,648: Line 6,648:
else
else
-- CODE
-- CODE
end;</lang>
end;</syntaxhighlight>


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)
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,654: Line 6,654:
=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang Scala> if (n == 12) "twelve" else "not twelve"
<syntaxhighlight lang="scala"> if (n == 12) "twelve" else "not twelve"
today match {
today match {
Line 6,664: Line 6,664:
Accumulate_Sales
Accumulate_Sales
case _ => {}
case _ => {}
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 6,671: Line 6,671:
===Primitive===
===Primitive===
====if====
====if====
<lang>(if <test> <consequent> <alternate>)</lang>
<syntaxhighlight lang="text">(if <test> <consequent> <alternate>)</syntaxhighlight>
<lang>(if <test> <consequent>)</lang>
<syntaxhighlight lang="text">(if <test> <consequent>)</syntaxhighlight>
Example:
Example:
<lang scheme>(display
<syntaxhighlight lang="scheme">(display
(if (> 1 2)
(if (> 1 2)
"yes"
"yes"
Line 6,682: Line 6,682:
(if (> 1 2)
(if (> 1 2)
(- 1 2)))
(- 1 2)))
(newline)</lang>
(newline)</syntaxhighlight>
{{out}}
{{out}}
<pre>no
<pre>no
Line 6,689: Line 6,689:
===Derived===
===Derived===
====cond====
====cond====
<lang>(cond <clause1> <clause2> ...)</lang>
<syntaxhighlight lang="text">(cond <clause1> <clause2> ...)</syntaxhighlight>
Example:
Example:
<lang scheme>(display
<syntaxhighlight lang="scheme">(display
(cond ((> 1 2) "greater")
(cond ((> 1 2) "greater")
((< 1 2) "less")))
((< 1 2) "less")))
Line 6,699: Line 6,699:
((< 1 1) "less")
((< 1 1) "less")
(else "equal")))
(else "equal")))
(newline)</lang>
(newline)</syntaxhighlight>
{{out}}
{{out}}
<pre>less
<pre>less
Line 6,705: Line 6,705:


====case====
====case====
<lang>(case <key> <clause1> <clause2> ...)</lang>
<syntaxhighlight lang="text">(case <key> <clause1> <clause2> ...)</syntaxhighlight>
Example:
Example:
<lang scheme>(display
<syntaxhighlight lang="scheme">(display
(case (* 2 3)
(case (* 2 3)
((2 3 5 7) "prime")
((2 3 5 7) "prime")
Line 6,717: Line 6,717:
((w y) "semivowel")
((w y) "semivowel")
(else "consonant")))
(else "consonant")))
(newline)</lang>
(newline)</syntaxhighlight>
{{out}}
{{out}}
<pre>composite
<pre>composite
Line 6,742: Line 6,742:
There can be single or multiple statements.
There can be single or multiple statements.
An if-statement can have multiple elsif parts.
An if-statement can have multiple elsif parts.
<lang seed7>if condition then
<syntaxhighlight lang="seed7">if condition then
statement
statement
end if;
end if;
Line 6,764: Line 6,764:
else
else
statement3;
statement3;
end if;</lang>
end if;</syntaxhighlight>


=== case ===
=== case ===
<lang seed7>case i of
<syntaxhighlight lang="seed7">case i of
when {1, 4, 9}: # Executed if i is 1, 4 or 9
when {1, 4, 9}: # Executed if i is 1, 4 or 9
statement1;
statement1;
Line 6,776: Line 6,776:
otherwise:
otherwise:
statement4;
statement4;
end case;</lang>
end case;</syntaxhighlight>


=={{header|SIMPOL}}==
=={{header|SIMPOL}}==
===if-else if-else===
===if-else if-else===
<lang simpol>if x == 1
<syntaxhighlight lang="simpol">if x == 1
foo()
foo()
else if x == 2
else if x == 2
Line 6,786: Line 6,786:
else
else
foobar()
foobar()
end if</lang>
end if</syntaxhighlight>


===ternary if function===
===ternary if function===
<lang simpol>.if(x == 1, "hello", "world")</lang>
<syntaxhighlight lang="simpol">.if(x == 1, "hello", "world")</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
Line 6,799: Line 6,799:
'''if''' X=Y '''then''' K:=I
'''if''' X=Y '''then''' K:=I
An example:
An example:
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN
INTEGER i,j;
INTEGER i,j;
i:=1; j:=2;
i:=1; j:=2;
Line 6,817: Line 6,817:
END;
END;
OutImage
OutImage
END</lang>
END</syntaxhighlight>
Simula 67 has also a switch structure:
Simula 67 has also a switch structure:
declaration::= '''switch''' switch:=list_of labels
declaration::= '''switch''' switch:=list_of labels
statement::= '''goto''' switch[expression]
statement::= '''goto''' switch[expression]
An example:
An example:
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN
INTEGER i,j;
INTEGER i,j;
SWITCH target:=L1,L2,L3;
SWITCH target:=L1,L2,L3;
Line 6,832: Line 6,832:
L3: OutText("CC");
L3: OutText("CC");
OutImage
OutImage
END</lang>
END</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
===ifTrue/ifFalse===
===ifTrue/ifFalse===
<lang slate>"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)"
<syntaxhighlight lang="slate">"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)"
balance > 0
balance > 0
ifTrue: [inform: 'still sitting pretty!'.]
ifTrue: [inform: 'still sitting pretty!'.]
ifFalse: [inform: 'No money till payday!'.].</lang>
ifFalse: [inform: 'No money till payday!'.].</syntaxhighlight>




===caseOf:otherwise:===
===caseOf:otherwise:===
<lang slate>c@(Net URLPathEncoder traits) convert
<syntaxhighlight lang="slate">c@(Net URLPathEncoder traits) convert
[ | byte1 byte2 byte3 digit1 digit2|
[ | byte1 byte2 byte3 digit1 digit2|
[c in isAtEnd] whileFalse:
[c in isAtEnd] whileFalse:
Line 6,857: Line 6,857:
} otherwise: [c out nextPut: byte1].
} otherwise: [c out nextPut: byte1].
].
].
].</lang>
].</syntaxhighlight>


===whileTrue:/whileFalse:===
===whileTrue:/whileFalse:===


<lang slate>[p isAtEnd] whileFalse: [p next evaluate]].</lang>
<syntaxhighlight lang="slate">[p isAtEnd] whileFalse: [p next evaluate]].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 6,877: Line 6,877:
Conditionals in Smalltalk are really messages sent to Boolean objects.
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):
<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):
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
balance > 0
balance > 0
ifTrue: [Transcript cr; show: 'still sitting pretty!'.]
ifTrue: [Transcript cr; show: 'still sitting pretty!'.]
Line 6,889: Line 6,889:
ifFalse:[ self gotoHappyHour ]
ifFalse:[ self gotoHappyHour ]
ifTrue:[ self noDrinksToday ].
ifTrue:[ self noDrinksToday ].
</syntaxhighlight>
</lang>


You can also use them as the ternary operator
You can also use them as the ternary operator


<lang smalltalk>abs := x > 0 ifTrue: [ x ] ifFalse: [ x negated ]</lang>
<syntaxhighlight lang="smalltalk">abs := x > 0 ifTrue: [ x ] ifFalse: [ x negated ]</syntaxhighlight>


Or get the alternatives from somewhere else (for example, passed as parameter)
Or get the alternatives from somewhere else (for example, passed as parameter)


<lang smalltalk>...
<syntaxhighlight lang="smalltalk">...
trueAction := [ ... do something ].
trueAction := [ ... do something ].
falseAction := [ ... do something else ...].
falseAction := [ ... do something else ...].
...
...
abs := x > 0 ifTrue:trueAction ifFalse:falseAction. "3)"</lang>
abs := x > 0 ifTrue:trueAction ifFalse:falseAction. "3)"</syntaxhighlight>


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).
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,908: Line 6,908:


===Switch Case===
===Switch Case===
<lang smalltalk>|x|
<syntaxhighlight lang="smalltalk">|x|
x := 1.
x := 1.
value :=
value :=
Line 6,916: Line 6,916:
[3]->['three']
[3]->['three']
}
}
otherwise:['none of them'].</lang>
otherwise:['none of them'].</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
SNOBOL4 has no structured programming features, but the two constructs in question could be easily emulated with FAILURE/SUCCESS and indirect jumps
SNOBOL4 has no structured programming features, but the two constructs in question could be easily emulated with FAILURE/SUCCESS and indirect jumps


<lang snobol> A = "true"
<syntaxhighlight lang="snobol"> A = "true"
* "if-then-else"
* "if-then-else"
if A "true" :s(goTrue)f(goFalse)
if A "true" :s(goTrue)f(goFalse)
Line 6,934: Line 6,934:
default output = "A is neither FALSE nor TRUE"
default output = "A is neither FALSE nor TRUE"
esac
esac
end</lang>
end</syntaxhighlight>


=={{header|SNUSP}}==
=={{header|SNUSP}}==


<lang snusp>$==?\==zero=====!/==#
<syntaxhighlight lang="snusp">$==?\==zero=====!/==#
\==non zero==/</lang>
\==non zero==/</syntaxhighlight>


'''?''' is the only conditional operator. It skips one character if the current cell is zero.
'''?''' is the only conditional operator. It skips one character if the current cell is zero.
Line 6,953: Line 6,953:
If statement:
If statement:


<lang sparkling>var odd = 13;
<syntaxhighlight lang="sparkling">var odd = 13;
if odd % 2 != 0 {
if odd % 2 != 0 {
print("odd");
print("odd");
}</lang>
}</syntaxhighlight>


If-else statement:
If-else statement:


<lang sparkling>var odd = 13;
<syntaxhighlight lang="sparkling">var odd = 13;
if odd % 2 != 0 {
if odd % 2 != 0 {
print("odd");
print("odd");
} else {
} else {
print("even");
print("even");
}</lang>
}</syntaxhighlight>


If and if-else statements can be chained:
If and if-else statements can be chained:


<lang sparkling>var nodiv3 = 13;
<syntaxhighlight lang="sparkling">var nodiv3 = 13;
if nodiv3 % 3 == 0 {
if nodiv3 % 3 == 0 {
print("divisible by 3");
print("divisible by 3");
Line 6,976: Line 6,976:
} else {
} else {
print("gives 2 remainder");
print("gives 2 remainder");
}</lang>
}</syntaxhighlight>


There's no "switch-case" statement in Sparkling yet, but it's work in progress.
There's no "switch-case" statement in Sparkling yet, but it's work in progress.
Line 6,983: Line 6,983:
{{works with|MS SQL|2005}}
{{works with|MS SQL|2005}}
===Conditional Expression===
===Conditional Expression===
<lang sql>case when a then b else c end
<syntaxhighlight lang="sql">case when a then b else c end


declare @n int
declare @n int
Line 6,991: Line 6,991:
--If/ElseIf expression
--If/ElseIf expression
set @n=5
set @n=5
print case when @n=3 then 'Three' when @n=4 then 'Four' else 'Other' end</lang>
print case when @n=3 then 'Three' when @n=4 then 'Four' else 'Other' end</syntaxhighlight>


===If/Else===
===If/Else===
<lang sql>declare @n int
<syntaxhighlight lang="sql">declare @n int
set @n=123
set @n=123
if @n=123
if @n=123
Line 7,002: Line 7,002:
ELSE
ELSE
if @n=124 print 'one two four'
if @n=124 print 'one two four'
else print 'other'</lang>
else print 'other'</syntaxhighlight>


=={{header|SSEM}}==
=={{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.
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.
<lang ssem>01010000000000100000000000000000 -10 to c
<syntaxhighlight lang="ssem">01010000000000100000000000000000 -10 to c
00000000000000110000000000000000 Test
00000000000000110000000000000000 Test
01110000000000000000000000000000 14 to CI</lang>
01110000000000000000000000000000 14 to CI</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
Line 7,014: Line 7,014:
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.
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.


<lang stata>clear
<syntaxhighlight lang="stata">clear
set obs 4
set obs 4
gen a = cond(mod(_n, 2)==1, "A", "B")
gen a = cond(mod(_n, 2)==1, "A", "B")
Line 7,024: Line 7,024:
| A |
| A |
| B |
| B |
+---+</lang>
+---+</syntaxhighlight>


=== if command ===
=== 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.
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.


<lang stata>program isprime
<syntaxhighlight lang="stata">program isprime
sca n = `0'
sca n = `0'
sca p = 1
sca p = 1
Line 7,062: Line 7,062:


isprime `=10^12-11'
isprime `=10^12-11'
999999999989 is prime.</lang>
999999999989 is prime.</syntaxhighlight>


=== if expression ===
=== 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.
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.


<lang stata>clear
<syntaxhighlight lang="stata">clear
set obs 100
set obs 100
count
count
100
100
count if mod(_n, 3)==0
count if mod(_n, 3)==0
33</lang>
33</syntaxhighlight>


=== if statement in Mata ===
=== 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.
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.


<lang stata>function isprime(n) {
<syntaxhighlight lang="stata">function isprime(n) {
if (n<5) return(n==2 | n==3)
if (n<5) return(n==2 | n==3)
else if (mod(n, 2)==0) return(0)
else if (mod(n, 2)==0) return(0)
Line 7,089: Line 7,089:


isprime(10^12-11)
isprime(10^12-11)
1</lang>
1</syntaxhighlight>


=== ternary operator in Mata ===
=== ternary operator in Mata ===
Line 7,095: Line 7,095:
See [https://www.stata.com/help.cgi?m2_op_conditional Stata help]. Here is a recursive implementation of the Fibonacci sequence, to illustrate.
See [https://www.stata.com/help.cgi?m2_op_conditional Stata help]. Here is a recursive implementation of the Fibonacci sequence, to illustrate.


<lang stata>function fib(n) {
<syntaxhighlight lang="stata">function fib(n) {
return(n<2 ? n : fib(n-1)+fib(n-2))
return(n<2 ? n : fib(n-1)+fib(n-2))
}
}


fib(10)
fib(10)
55</lang>
55</syntaxhighlight>


=={{header|Swahili}}==
=={{header|Swahili}}==
===if-else if-else (kama-au-sivyo)===
===if-else if-else (kama-au-sivyo)===
<lang swahili>kama (kweli) {
<syntaxhighlight lang="swahili">kama (kweli) {
andika("statement")
andika("statement")
} au (kweli /* condition */) {
} au (kweli /* condition */) {
Line 7,112: Line 7,112:
} sivyo {
} sivyo {
andika("statement")
andika("statement")
}</lang>
}</syntaxhighlight>


=={{header|Tailspin}}==
=={{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
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 "-> #").
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 "-> #").
<lang tailspin>
<syntaxhighlight lang="tailspin">
templates foo
templates foo
when <=0> do 'zero' -> !OUT::write
when <=0> do 'zero' -> !OUT::write
Line 7,126: Line 7,126:
otherwise 'odd' -> !OUT::write
otherwise 'odd' -> !OUT::write
end foo
end foo
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==


===if-then-else===
===if-then-else===
<lang tcl>if {$foo == 3} {
<syntaxhighlight lang="tcl">if {$foo == 3} {
puts "foo is three"
puts "foo is three"
} elseif {$foo == 4} {
} elseif {$foo == 4} {
Line 7,137: Line 7,137:
} else {
} else {
puts "foo is neither three nor four"
puts "foo is neither three nor four"
}</lang>
}</syntaxhighlight>
or (using the ternary operator of expressions)
or (using the ternary operator of expressions)
<lang tcl>set result [expr { $foo == 3 ? "three" : "not three" }]</lang>
<syntaxhighlight lang="tcl">set result [expr { $foo == 3 ? "three" : "not three" }]</syntaxhighlight>


===switch===
===switch===
<lang tcl>switch -- $foo {
<syntaxhighlight lang="tcl">switch -- $foo {
3 {puts "foo is three"}
3 {puts "foo is three"}
4 {puts "foo is four"}
4 {puts "foo is four"}
default {puts "foo is something else"}
default {puts "foo is something else"}
}</lang>
}</syntaxhighlight>
Note that the <tt>switch</tt> command can also use glob matching (like <tt>case</tt> in the Bourne Shell) or regular-expression matching.
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 7,154: Line 7,154:


===If Statement===
===If Statement===
<lang tern>if(a > b)
<syntaxhighlight lang="tern">if(a > b)
println(a);</lang>
println(a);</syntaxhighlight>


===If Else Statement===
===If Else Statement===
<lang tern>if(a > b) {
<syntaxhighlight lang="tern">if(a > b) {
println(a);
println(a);
} else {
} else {
println(b);
println(b);
}</lang>
}</syntaxhighlight>


===Unless Statement===
===Unless Statement===
<lang tern>unless(a > b) {
<syntaxhighlight lang="tern">unless(a > b) {
println(b);
println(b);
} else {
} else {
println(a);
println(a);
}</lang>
}</syntaxhighlight>


===Switch Statement===
===Switch Statement===
<lang tern>switch(a) {
<syntaxhighlight lang="tern">switch(a) {
case 10:
case 10:
case 11:
case 11:
Line 7,179: Line 7,179:
default:
default:
println(b);
println(b);
}</lang>
}</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 7,186: Line 7,186:
'''Basic form'''
'''Basic form'''
<br> with only one statement for the true part:
<br> with only one statement for the true part:
<lang ti83b>If condition
<syntaxhighlight lang="ti83b">If condition
statement</lang>
statement</syntaxhighlight>
or in one line
or in one line
<lang ti83b>If condition : statement</lang>
<syntaxhighlight lang="ti83b">If condition : statement</syntaxhighlight>


'''If-Then form'''
'''If-Then form'''
<lang ti83b>If condition
<syntaxhighlight lang="ti83b">If condition
Then
Then
statements
statements
End</lang>
End</syntaxhighlight>


'''If-Then-Else form'''
'''If-Then-Else form'''
<lang ti83b>If condition
<syntaxhighlight lang="ti83b">If condition
Then
Then
statements
statements
Else
Else
statements
statements
End</lang>
End</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
Line 7,210: Line 7,210:
( condition ) ( quote ) ifTrue
( condition ) ( quote ) ifTrue


<lang toka>100 100 = [ ." True\n" ] ifTrue
<syntaxhighlight lang="toka">100 100 = [ ." True\n" ] ifTrue
100 200 = [ ." True\n" ] ifTrue</lang>
100 200 = [ ." True\n" ] ifTrue</syntaxhighlight>


===ifFalse===
===ifFalse===
( condition ) ( quote ) ifFalse
( condition ) ( quote ) ifFalse


<lang toka>100 100 = [ ." True\n" ] ifFalse
<syntaxhighlight lang="toka">100 100 = [ ." True\n" ] ifFalse
100 200 = [ ." True\n" ] ifFalse</lang>
100 200 = [ ." True\n" ] ifFalse</syntaxhighlight>


===ifTrueFalse===
===ifTrueFalse===
( condition ) ( true quote ) ( false quote ) ifTrueFalse
( condition ) ( true quote ) ( false quote ) ifTrueFalse


<lang toka>100 100 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse
<syntaxhighlight lang="toka">100 100 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse
100 200 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse</lang>
100 200 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==
Line 7,229: Line 7,229:
===if-then-else===
===if-then-else===


<lang tqs>// numbers and objects
<syntaxhighlight lang="tqs">// numbers and objects
if(%num == 1)
if(%num == 1)
{
{
Line 7,255: Line 7,255:
{
{
deusEx();
deusEx();
}</lang>
}</syntaxhighlight>


===switch===
===switch===


<lang tqs>// numbers and objects
<syntaxhighlight lang="tqs">// numbers and objects
switch(%num)
switch(%num)
{
{
Line 7,287: Line 7,287:
default:
default:
somethingElse();
somethingElse();
}</lang>
}</syntaxhighlight>


===conditional (ternary) operator (?:)===
===conditional (ternary) operator (?:)===


<lang tqs>%formatted = %str @ ((getSubStr(%str,strLen(%str) - 1,1) $= "s") ? "'" : "'s");</lang>
<syntaxhighlight lang="tqs">%formatted = %str @ ((getSubStr(%str,strLen(%str) - 1,1) $= "s") ? "'" : "'s");</syntaxhighlight>


=={{header|Trith}}==
=={{header|Trith}}==
===branch===
===branch===
<lang trith>true ["yes" print] ["no" print] branch</lang>
<syntaxhighlight lang="trith">true ["yes" print] ["no" print] branch</syntaxhighlight>
===when===
===when===
<lang trith>true ["yes" print] when</lang>
<syntaxhighlight lang="trith">true ["yes" print] when</syntaxhighlight>
===unless===
===unless===
<lang trith>false ["no" print] unless</lang>
<syntaxhighlight lang="trith">false ["no" print] unless</syntaxhighlight>




=={{header|True BASIC}}==
=={{header|True BASIC}}==
<lang basic>
<syntaxhighlight lang="basic">
! IF-ELSEIF-ELSE-END IF
! IF-ELSEIF-ELSE-END IF
! SELECT-CASE
! SELECT-CASE
Line 7,338: Line 7,338:


ON expresión Gosub label1, label2 ELSE label3
ON expresión Gosub label1, label2 ELSE label3
</syntaxhighlight>
</lang>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
===IF ELSEIF ELSE ENDIF===
===IF ELSEIF ELSE ENDIF===
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT


Line 7,353: Line 7,353:
---> do something
---> do something
ENDIF
ENDIF
</syntaxhighlight>
</lang>
===SELECT CASE DEFAULT ENDSELECT===
===SELECT CASE DEFAULT ENDSELECT===
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT


Line 7,370: Line 7,370:
---> do something
---> do something
ENDSELECT
ENDSELECT
</syntaxhighlight>
</lang>


=={{header|TXR}}==
=={{header|TXR}}==
Line 7,382: Line 7,382:
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:
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:


<lang txr>
<syntaxhighlight lang="txr">
@(choose :shortest x)
@(choose :shortest x)
@x:@y
@x:@y
Line 7,389: Line 7,389:
@(or)
@(or)
@x+@y
@x+@y
@(end)</lang>
@(end)</syntaxhighlight>


Suppose the input is something which can match all three patterns in different ways:
Suppose the input is something which can match all three patterns in different ways:
Line 7,408: Line 7,408:
For instance:
For instance:


<lang txr>@(all)
<syntaxhighlight lang="txr">@(all)
@x:y@
@x:y@
@z<-@w
@z<-@w
Line 7,415: Line 7,415:
We have a match: (x, y, z, w) = (@x, @y, @z, @w).
We have a match: (x, y, z, w) = (@x, @y, @z, @w).
@(end)
@(end)
@(end)</lang>
@(end)</syntaxhighlight>


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 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:
If previously bound variable is bound again, it must be to an identical piece of text:


<lang txr>@# match a line which contains some piece of text x
<syntaxhighlight lang="txr">@# match a line which contains some piece of text x
@# after the rightmost occurence of : such that the same piece
@# after the rightmost occurence of : such that the same piece
@# of text also occurs at the start of the line preceded by -->
@# of text also occurs at the start of the line preceded by -->
Line 7,427: Line 7,427:
@(and)
@(and)
-->@x@/.*/
-->@x@/.*/
@(end)</lang>
@(end)</syntaxhighlight>


<pre>$ echo "-->asdfhjig:asdf" | txr -B weird.txr -
<pre>$ echo "-->asdfhjig:asdf" | txr -B weird.txr -
Line 7,443: Line 7,443:
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.
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.


<lang sh>if test 3 -lt 5; then echo '3 is less than 5'; fi</lang>
<syntaxhighlight lang="sh">if test 3 -lt 5; then echo '3 is less than 5'; fi</syntaxhighlight>


==== Else and elif ====
==== Else and elif ====
Line 7,449: Line 7,449:
There are optional <code>elif</code> (else if) and <code>else</code> clauses.
There are optional <code>elif</code> (else if) and <code>else</code> clauses.


<lang sh>if test 4 -ge 6; then
<syntaxhighlight lang="sh">if test 4 -ge 6; then
echo '4 is greater than or equal to 6'
echo '4 is greater than or equal to 6'
elif test 4 -lt 6; then
elif test 4 -lt 6; then
Line 7,455: Line 7,455:
else
else
echo '4 compares not to 6'
echo '4 compares not to 6'
fi</lang>
fi</syntaxhighlight>


==== Switch conditionals ====
==== Switch conditionals ====
Line 7,461: Line 7,461:
The Unix shell provides support for multibranch switch conditional constructs using the case statement:
The Unix shell provides support for multibranch switch conditional constructs using the case statement:


<lang sh>case value in
<syntaxhighlight lang="sh">case value in
choicea)
choicea)
foo
foo
Line 7,468: Line 7,468:
bar
bar
;;
;;
esac</lang>
esac</syntaxhighlight>


==== Conditional branching using operators ====
==== Conditional branching using operators ====
Line 7,474: Line 7,474:
One can also use <code>&&</code> and <code>||</code> as conditional structures; see [[short-circuit evaluation#UNIX Shell]].
One can also use <code>&&</code> and <code>||</code> as conditional structures; see [[short-circuit evaluation#UNIX Shell]].


<lang sh>test 3 -lt 5 && echo '3 is less than 5'
<syntaxhighlight 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'</lang>
test 4 -ge 6 || echo '4 is not greater than or equal to 6'</syntaxhighlight>


==== Conditional loops ====
==== Conditional loops ====
Line 7,481: Line 7,481:
The Unix shell also supports conditional loops:
The Unix shell also supports conditional loops:


<lang sh># This is a while loop
<syntaxhighlight lang="sh"># This is a while loop
l=1
l=1
while [ l -le 5 ]; do
while [ l -le 5 ]; do
Line 7,491: Line 7,491:
until [ l -eq 5 ]; do
until [ l -eq 5 ]; do
echo $l
echo $l
done</lang>
done</syntaxhighlight>


==={{header|C Shell}}===
==={{header|C Shell}}===
The single-line <code>if</code> syntax is <code>if (''expression'') ''simple-command''</code>.
The single-line <code>if</code> syntax is <code>if (''expression'') ''simple-command''</code>.


<lang csh>if (3 < 5) echo '3 is less than 5'
<syntaxhighlight lang="csh">if (3 < 5) echo '3 is less than 5'
if ({ grep -q ^root: /etc/passwd }) echo 'passwd has root'</lang>
if ({ grep -q ^root: /etc/passwd }) echo 'passwd has root'</syntaxhighlight>


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.
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.


<lang csh>if (4 >= 6) then
<syntaxhighlight lang="csh">if (4 >= 6) then
echo '4 is greater than or equal to 6'
echo '4 is greater than or equal to 6'
else if (4 < 6) then
else if (4 < 6) then
Line 7,507: Line 7,507:
else
else
echo '4 compares not to 6'
echo '4 compares not to 6'
endif</lang>
endif</syntaxhighlight>


=={{header|Unison}}==
=={{header|Unison}}==
<lang Unison>factorial : Nat -> Nat
<syntaxhighlight lang="unison">factorial : Nat -> Nat
factorial x =
factorial x =
if x == 0 then 1
if x == 0 then 1
else
else
x * fac (Nat.drop x 1)</lang>
x * fac (Nat.drop x 1)</syntaxhighlight>


=={{header|V}}==
=={{header|V}}==
===ifThenElse===
===ifThenElse===
<lang v>[true]
<syntaxhighlight lang="v">[true]
['is true' puts]
['is true' puts]
['is false' puts]
['is false' puts]
ifte
ifte


=is true</lang>
=is true</syntaxhighlight>


===ifThen===
===ifThen===
<lang v>[true]
<syntaxhighlight lang="v">[true]
['is true' puts]
['is true' puts]
if
if
=is true</lang>
=is true</syntaxhighlight>


===When===
===When===
<lang v>3 [
<syntaxhighlight lang="v">3 [
[1 =] [1 *]
[1 =] [1 *]
[2 =] [10 *]
[2 =] [10 *]
Line 7,539: Line 7,539:
] when
] when


=300</lang>
=300</syntaxhighlight>
===Choice===
===Choice===
<lang v>true
<syntaxhighlight lang="v">true
1 2
1 2
choice
choice
Line 7,551: Line 7,551:
choice
choice


=2</lang>
=2</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
===If Else End If===
===If Else End If===
<syntaxhighlight lang="vb">
<lang vb>
Sub C_S_If()
Sub C_S_If()
Dim A$, B$
Dim A$, B$
Line 7,580: Line 7,580:
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."
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</lang>
End Sub</syntaxhighlight>


===If ElseIf Else End If===
===If ElseIf Else End If===
<lang vb>Sub C_S_ElseIf()
<syntaxhighlight lang="vb">Sub C_S_ElseIf()
Dim A$, B$
Dim A$, B$


Line 7,598: Line 7,598:
Debug.Print A & " < " & B
Debug.Print A & " < " & B
End If
End If
End Sub</lang>
End Sub</syntaxhighlight>
===Select Case===
===Select Case===
<lang vb>Sub C_S_Select_Case()
<syntaxhighlight lang="vb">Sub C_S_Select_Case()
'With Strings
'With Strings
Dim A$, C&
Dim A$, C&
Line 7,651: Line 7,651:
Debug.Print "C >= 20"
Debug.Print "C >= 20"
End Select
End Select
End Sub</lang>
End Sub</syntaxhighlight>
===Inline IF===
===Inline IF===
<lang vb>Sub C_S_IIF()
<syntaxhighlight lang="vb">Sub C_S_IIF()
Dim myName
Dim myName
myName = 2
myName = 2
Line 7,659: Line 7,659:
'return : Justin
'return : Justin
End Sub
End Sub
</syntaxhighlight>
</lang>
===Switch===
===Switch===
<lang vb>Sub C_S_Switch()
<syntaxhighlight lang="vb">Sub C_S_Switch()
Dim myName
Dim myName
myName = 2
myName = 2
Line 7,667: Line 7,667:
'return : Justin
'return : Justin
End Sub
End Sub
</syntaxhighlight>
</lang>


=={{header|VBScript}}==
=={{header|VBScript}}==
===if-then-else===
===if-then-else===
Block form:
Block form:
<lang vb>If condition1 Then
<syntaxhighlight lang="vb">If condition1 Then
statement
statement
End If
End If
Line 7,686: Line 7,686:
statement
statement
End If
End If
</syntaxhighlight>
</lang>
Line form:
Line form:
<lang vb>If condition Then statement
<syntaxhighlight lang="vb">If condition Then statement


If condition Then statement Else statement</lang>
If condition Then statement Else statement</syntaxhighlight>
===select-case===
===select-case===
<lang vb>Select Case Expression
<syntaxhighlight lang="vb">Select Case Expression
Case Value1: statement
Case Value1: statement
Case Value2: statement
Case Value2: statement
Line 7,710: Line 7,710:
Case Else
Case Else
statements
statements
End Select</lang>
End Select</syntaxhighlight>


=={{header|Verbexx}}==
=={{header|Verbexx}}==
<lang verbexx>@VAR a b = 1 2;
<syntaxhighlight lang="verbexx">@VAR a b = 1 2;


// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
Line 7,782: Line 7,782:
n = 0 @CASE results: n == 0(1)
n = 0 @CASE results: n == 0(1)
n = 1 @CASE results: n == 1(2c)
n = 1 @CASE results: n == 1(2c)
n = 2 @CASE results: else</lang>
n = 2 @CASE results: else</syntaxhighlight>




=={{header|Verilog}}==
=={{header|Verilog}}==
===if-else===
===if-else===
<syntaxhighlight lang="verilog">
<lang Verilog>
if( expr_booleana ) command1;
if( expr_booleana ) command1;
else command2;
else command2;
</syntaxhighlight>
</lang>


===case===
===case===
<syntaxhighlight lang="verilog">
<lang Verilog>
case( expr_booleana )
case( expr_booleana )
valor1: command1;
valor1: command1;
Line 7,800: Line 7,800:
default: commandN;
default: commandN;
endcase
endcase
</syntaxhighlight>
</lang>




Line 7,806: Line 7,806:
===if-then-else===
===if-then-else===
====Block form====
====Block form====
<lang vb>If condition Then
<syntaxhighlight lang="vb">If condition Then
statement
statement
End If
End If
Line 7,825: Line 7,825:
Else
Else
statement
statement
End If</lang>
End If</syntaxhighlight>


====Line form====
====Line form====
<lang vb>If condition Then statement
<syntaxhighlight lang="vb">If condition Then statement


If condition Then statement Else statement</lang>
If condition Then statement Else statement</syntaxhighlight>


===select-case===
===select-case===
<lang vb>Select Case Expression
<syntaxhighlight lang="vb">Select Case Expression
Case Value1: statement
Case Value1: statement
Case Value2: statement
Case Value2: statement
Line 7,852: Line 7,852:
statements
statements
End Select
End Select
</syntaxhighlight>
</lang>
===inline if-then-else===
===inline if-then-else===
<lang vb>IIf(expr, then-value, else-value)</lang>
<syntaxhighlight lang="vb">IIf(expr, then-value, else-value)</syntaxhighlight>
Example:
Example:
<lang vbnet> myName = 2
<syntaxhighlight lang="vbnet"> myName = 2
Debug.Print IIf(myName = 1, "John", "Jack")
Debug.Print IIf(myName = 1, "John", "Jack")
'return : "Jack")</lang>
'return : "Jack")</syntaxhighlight>


===inline switch===
===inline switch===
<lang vb>Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n,value-n]])</lang>
<syntaxhighlight lang="vb">Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n,value-n]])</syntaxhighlight>
Example:
Example:
<lang vb> myName = 2
<syntaxhighlight lang="vb"> myName = 2
Debug.Print Switch(myName = 1, "James", myName = 2, "Jacob", myName = 3, "Jeremy")
Debug.Print Switch(myName = 1, "James", myName = 2, "Jacob", myName = 3, "Jeremy")
'return : "Jacob"</lang>
'return : "Jacob"</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 7,871: Line 7,871:
===if-then-else===
===if-then-else===
''Basic''
''Basic''
<lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"
<syntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"


If a = b Then
If a = b Then
Line 7,877: Line 7,877:
Else
Else
result = "failed"
result = "failed"
End If</lang>
End If</syntaxhighlight>


''Condensed''
''Condensed''
<lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"
<syntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"


If a = b Then result = "passed" Else result = "failed"
If a = b Then result = "passed" Else result = "failed"
Line 7,892: Line 7,892:
Else
Else
result = "failed"
result = "failed"
End If</lang>
End If</syntaxhighlight>


===if-then-elseif===
===if-then-elseif===
<lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"
<syntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"


If a = b Then
If a = b Then
Line 7,903: Line 7,903:
Else
Else
result = "impossible"
result = "impossible"
End If</lang>
End If</syntaxhighlight>


===select-case-else===
===select-case-else===
<lang vbnet>Dim result As String, a As String = "pants", b As String = "glasses"
<syntaxhighlight lang="vbnet">Dim result As String, a As String = "pants", b As String = "glasses"


Select Case a
Select Case a
Line 7,914: Line 7,914:
Case Else
Case Else
result = "impossible"
result = "impossible"
End Select</lang>
End Select</syntaxhighlight>


===inline-conditional===
===inline-conditional===
<lang vbnet>Imports Microsoft.VisualBasic
<syntaxhighlight lang="vbnet">Imports Microsoft.VisualBasic


...
...
Line 7,923: Line 7,923:
Dim result As String = CType(IIf("pants" = "glasses", "passed", "failed"), String) 'VB 1-8
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</lang>
Dim result As String = If("pants" = "glasses", "passed", "failed") 'VB 9</syntaxhighlight>


===generic-inline-conditional===
===generic-inline-conditional===
{{works with|Visual Basic .NET|8.0}}
{{works with|Visual Basic .NET|8.0}}
<lang vbnet>Imports Microsoft.VisualBasic
<syntaxhighlight lang="vbnet">Imports Microsoft.VisualBasic


...
...
Line 7,937: Line 7,937:
...
...


Dim result As String = IIf2("pants" = "glasses", "passed", "failed") ' type is inferred</lang>
Dim result As String = IIf2("pants" = "glasses", "passed", "failed") ' type is inferred</syntaxhighlight>


===generic-inline-conditional===
===generic-inline-conditional===
'''Language Version:''' 9.0+
'''Language Version:''' 9.0+


<lang vbnet>Dim result As String = If("pants" = "glasses", "passed", "failed") ' type is inferred</lang>
<syntaxhighlight lang="vbnet">Dim result As String = If("pants" = "glasses", "passed", "failed") ' type is inferred</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
Line 7,948: Line 7,948:
===If===
===If===
Simplest usage is,
Simplest usage is,
<lang vlang>if boolean_expression {
<syntaxhighlight lang="vlang">if boolean_expression {
statements
statements
}</lang>
}</syntaxhighlight>
The braces are required, even around a single statement.
The braces are required, even around a single statement.
<lang vlang>if boolean_expression {
<syntaxhighlight lang="vlang">if boolean_expression {
statements
statements
} else {
} else {
other
other
statements
statements
}</lang>
}</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,
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,
<lang vlang>if boolean_expression1 {
<syntaxhighlight lang="vlang">if boolean_expression1 {
statements
statements
} else if boolean_expression2 {
} else if boolean_expression2 {
otherStatements
otherStatements
}
}
</syntaxhighlight>
</lang>


===Match===
===Match===
Simple usage is,
Simple usage is,
<lang vlang>match true {
<syntaxhighlight lang="vlang">match true {
boolean_expression1 {
boolean_expression1 {
statements
statements
Line 7,981: Line 7,981:
statements
statements
}
}
}</lang>
}</syntaxhighlight>
Because match can work with any number of arbitrary boolean expressions, it replaces if/elseif chains often found in other programming languages.
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,
Match can also switch on the value of an expression, as in,
<lang vlang>switch expression_of_any_type {
<syntaxhighlight lang="vlang">switch expression_of_any_type {
value1 {
value1 {
statements
statements
Line 7,994: Line 7,994:
}
}
else {}
else {}
}</lang>
}</syntaxhighlight>
As shown, multiple values can be listed for a single case clause.
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.
Since vlang is statically typed, the types of value1, 2, 3, and 4 must match the type of the expression.
Line 8,001: Line 8,001:


===if-then-else===
===if-then-else===
<lang vorpal>if(condition){
<syntaxhighlight lang="vorpal">if(condition){
result = 'met'
result = 'met'
}
}
else{
else{
result = 'not met'
result = 'not met'
}</lang>
}</syntaxhighlight>


=={{header|Woma}}==
=={{header|Woma}}==
Line 8,013: Line 8,013:
===break-if===
===break-if===
Valid inside of a <@> (loop) block.
Valid inside of a <@> (loop) block.
<lang woma><%>condition</lang>
<syntaxhighlight lang="woma"><%>condition</syntaxhighlight>


===continue-if===
===continue-if===
Valid inside of a <@> (loop) block.
Valid inside of a <@> (loop) block.
<lang woma><$>condition</lang>
<syntaxhighlight lang="woma"><$>condition</syntaxhighlight>


===if statement===
===if statement===
Valid inside of a function or a <@> (loop) block.
Valid inside of a function or a <@> (loop) block.
<lang woma>condition = True
<syntaxhighlight lang="woma">condition = True
condition<?>print(condition)</lang>
condition<?>print(condition)</syntaxhighlight>


=={{header|Wrapl}}==
=={{header|Wrapl}}==
Line 8,028: Line 8,028:
===simple conditional===
===simple conditional===
Conditionals in Wrapl are expressions. Either success or failure can be omitted from the expression.
Conditionals in Wrapl are expressions. Either success or failure can be omitted from the expression.
<lang wrapl>condition => success // failure
<syntaxhighlight lang="wrapl">condition => success // failure
condition => success
condition => success
condition // failure</lang>
condition // failure</syntaxhighlight>


===goal directed evaluation===
===goal directed evaluation===
Wrapl's goal directed evaluation can be used to control conditional execution.
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.
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.
<lang wrapl>condition & success</lang>
<syntaxhighlight lang="wrapl">condition & success</syntaxhighlight>
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.
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.
<lang wrapl>condition | failure</lang>
<syntaxhighlight lang="wrapl">condition | failure</syntaxhighlight>


=={{header|Wren}}==
=={{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.
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.
<lang ecmascript>for (b in [true, false]) {
<syntaxhighlight lang="ecmascript">for (b in [true, false]) {
if (b) {
if (b) {
System.print(true)
System.print(true)
Line 8,058: Line 8,058:


System.print()
System.print()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 8,077: Line 8,077:
===ifs/elseifs/elses===
===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.
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)
if(i>1)
DoSomething
DoSomething


FailedSoContinueCodeExecution.
FailedSoContinueCodeExecution.
</syntaxhighlight>
</lang>
There are actually a number of ways to implement that in assembly. The most typical way would be something like..
There are actually a number of ways to implement that in assembly. The most typical way would be something like..
<lang asm>
<syntaxhighlight lang="asm">
cmp i, 1
cmp i, 1
jg _DoSomething
jg _DoSomething
FailedSoContinueCodeExecution
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
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)
if(i>1)
DoSomething
DoSomething
Line 8,096: Line 8,096:
DoSomethingElse
DoSomethingElse
FailedSoContinueCodeExecution
FailedSoContinueCodeExecution
</syntaxhighlight>
</lang>
In this case, we can use our previous example as a skeleton.
In this case, we can use our previous example as a skeleton.
<lang asm>
<syntaxhighlight lang="asm">
cmp i, 1
cmp i, 1
jg _DoSomething
jg _DoSomething
jle _DoSomethingElse
jle _DoSomethingElse
FailedSoContinueCodeExecution
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>
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>
<br>
One last commonly used condition.
One last commonly used condition.
<syntaxhighlight lang="c">
<lang c>
if(i==1)
if(i==1)
DoSomething
DoSomething
Line 8,113: Line 8,113:
DoSomethingElse
DoSomethingElse
FailedSoContinueExecution
FailedSoContinueExecution
</syntaxhighlight>
</lang>


In this case, we'd do this.
In this case, we'd do this.
<lang asm>
<syntaxhighlight lang="asm">
cmp i, 1
cmp i, 1
je _DoSomething
je _DoSomething
jne _DoSomethingElse
jne _DoSomethingElse
FailedSoContinueExecution
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>
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.
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 8,128: Line 8,128:
===If===
===If===
An <code>IF</code> expression has the form <code>(IF <condition> <then-clause> <opt-else-clause>)</code>, for example:
An <code>IF</code> expression has the form <code>(IF <condition> <then-clause> <opt-else-clause>)</code>, for example:
<lang lisp>(if (eq s "Rosetta Code")
<syntaxhighlight lang="lisp">(if (eq s "Rosetta Code")
"The well-known programming chrestomathy site"
"The well-known programming chrestomathy site"
"Some other website, maybe, I dunno" )</lang>
"Some other website, maybe, I dunno" )</syntaxhighlight>
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.
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===
===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.
<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.
<lang lisp>(case s
<syntaxhighlight lang="lisp">(case s
("Rosetta Code" "Ah yes, the chrestomathy site")
("Rosetta Code" "Ah yes, the chrestomathy site")
("Stack Overflow" "Oh dear me, having problems are you?")
("Stack Overflow" "Oh dear me, having problems are you?")
("Github" "Say no more")
("Github" "Say no more")
(else "Sorry, never heard of it") )</lang>
(else "Sorry, never heard of it") )</syntaxhighlight>


===Cond===
===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.
<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.
<lang lisp>(cond
<syntaxhighlight lang="lisp">(cond
((eq s "Rosetta Code") "Chrestomathy site")
((eq s "Rosetta Code") "Chrestomathy site")
((> n 37) "Some other appropriate value, presumably")
((> 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") )</lang>
(t "If you're seeing me, s wasn't equal to Rosetta Code and n must have been 37 or below") )</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
Line 8,167: Line 8,167:
=={{header|XSLT}}==
=={{header|XSLT}}==
The <xsl:if> element allows simple conditional processing.
The <xsl:if> element allows simple conditional processing.
<lang xml><xsl:if test="condition">
<syntaxhighlight lang="xml"><xsl:if test="condition">
<!-- executed if XPath expression evaluates to true -->
<!-- executed if XPath expression evaluates to true -->
</xsl:if></lang>
</xsl:if></syntaxhighlight>
The <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements allow more general conditional processing.
The <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements allow more general conditional processing.
<lang xml><xsl:choose>
<syntaxhighlight lang="xml"><xsl:choose>
<xsl:when test="condition1">
<xsl:when test="condition1">
<!-- included if condition1 evaluates to true (like C `if`) -->
<!-- included if condition1 evaluates to true (like C `if`) -->
Line 8,187: Line 8,187:
<!-- (The `otherwise` element is optional) -->
<!-- (The `otherwise` element is optional) -->
</xsl:otherwise>
</xsl:otherwise>
</xsl:choose></lang>
</xsl:choose></syntaxhighlight>


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).
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).


<lang xml><xsl:if test="@attrib = 'foo'">...</xsl:if>
<syntaxhighlight lang="xml"><xsl:if test="@attrib = 'foo'">...</xsl:if>
<xsl:if test="position() != last()">...</xsl:if>
<xsl:if test="position() != last()">...</xsl:if>
<xsl:if test="not(false())">...</xsl:if>
<xsl:if test="not(false())">...</xsl:if>
Line 8,201: Line 8,201:
implicitly converted to boolean. -->
implicitly converted to boolean. -->
<xsl:if test="boolean($expr)">...</xsl:if>
<xsl:if test="boolean($expr)">...</xsl:if>
<xsl:if test="$expr">...</xsl:if></lang>
<xsl:if test="$expr">...</xsl:if></syntaxhighlight>




=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
<lang Yabasic>
// if-then-endif, switch / end switch
// if-then-endif, switch / end switch
// on gosub, on goto
// on gosub, on goto
Line 8,271: Line 8,271:
sentencia(s)
sentencia(s)
end while
end while
</syntaxhighlight>
</lang>




Line 8,282: Line 8,282:
We'll look at this example in C and in Z80 Assembly:
We'll look at this example in C and in Z80 Assembly:


<syntaxhighlight lang="c">
<lang C>
char x;
char x;
if (x == 20)
if (x == 20)
Line 8,291: Line 8,291:
{
{
doThat();
doThat();
}</lang>
}</syntaxhighlight>


<lang z80>cp 20
<syntaxhighlight lang="z80">cp 20
jr nz,Else
jr nz,Else
call doThis
call doThis
Line 8,300: Line 8,300:
Else:
Else:
call doThat
call doThat
done</lang>
done</syntaxhighlight>


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.
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,307: Line 8,307:


C code:
C code:
<lang C>if (x == 20)
<syntaxhighlight lang="c">if (x == 20)
{
{
DoSomething();
DoSomething();
}
}
// rest of program</lang>
// rest of program</syntaxhighlight>


Z80 Assembly code:
Z80 Assembly code:
<lang z80>
<syntaxhighlight lang="z80">
cp 20
cp 20
call z,DoSomething
call z,DoSomething
;rest of program</lang>
;rest of program</syntaxhighlight>


If the accumulator didn't equal 20, no <code>CALL</code> will actually take place.
If the accumulator didn't equal 20, no <code>CALL</code> will actually take place.
Line 8,323: Line 8,323:
===Switch===
===Switch===
Switch cases can be implemented in a few ways. The simplest way is by checking each value individually.
Switch cases can be implemented in a few ways. The simplest way is by checking each value individually.
<lang Z80>ld a,(HL) ;switch (HL)
<syntaxhighlight lang="z80">ld a,(HL) ;switch (HL)
cp 1 ;case (1)
cp 1 ;case (1)
jr nz,+ ;branch to next colon (note: not all assemblers support this syntax)
jr nz,+ ;branch to next colon (note: not all assemblers support this syntax)
Line 8,336: Line 8,336:
call HL_EQUALS_50
call HL_EQUALS_50
:
:
;rest of program</lang>
;rest of program</syntaxhighlight>


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:
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:
<lang z80>ld a,(HL) ;switch (HL)
<syntaxhighlight lang="z80">ld a,(HL) ;switch (HL)
cp 1 ;case (1)
cp 1 ;case (1)
jr nz,+ ;branch to next lone colon
jr nz,+ ;branch to next lone colon
Line 8,355: Line 8,355:
:
:
done:
done:
;rest of program</lang>
;rest of program</syntaxhighlight>


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.
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.


<lang z80>Dispatch: ;remember, you need to CALL this address for it to work properly. Otherwise your program will most likely crash.
<syntaxhighlight 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.
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
ld a,(hl) ;get the low byte of the function addr. you wish to call
Line 8,368: Line 8,368:
pop af
pop af
ld L,a ;store the low byte in L
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"</lang>
jp (HL) ;now you've jumped to the desired function. Its RET will return execution to the instruction just after "CALL Dispatch"</syntaxhighlight>


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.
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}}==
=={{header|zkl}}==
<lang zkl>if (x) y else z;
<syntaxhighlight lang="zkl">if (x) y else z;
if(a)b else if (c) else d; etc
if(a)b else if (c) else d; etc
x:=(if (a) b else c);
x:=(if (a) b else c);
Line 8,385: Line 8,385:
case(b){...}
case(b){...}
else {...} // case a C's default, has to be at the end
else {...} // case a C's default, has to be at the end
}</lang>
}</syntaxhighlight>


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
const builtin = @import("builtin");
const builtin = @import("builtin");


Line 8,450: Line 8,450:


// TODO Arithmetic if once https://github.com/ziglang/zig/issues/8220 is finished
// TODO Arithmetic if once https://github.com/ziglang/zig/issues/8220 is finished
}</lang>
}</syntaxhighlight>


{{omit from|GUISS}}
{{omit from|GUISS}}