Conditional structures: Difference between revisions
m
syntax highlighting fixup automation
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 16:
=={{header|11l}}==
===if-else===
<
foo()
E I x == 1
bar()
E
baz()</
===switch===
<
0
foo()
Line 30:
bar()
E
baz()</
=={{header|360 Assembly}}==
Here are the branch mnemonic opcodes:
<
B label Unconditional
BR Rx "
Line 81:
BNMR Rx "
BNZ label Branch if Not Zero
BNZR Rx "</
The ASM (Assembler Structured Macros) toolkit brings structures to IBM assembler 360.
<
opcode,op1,rel,op2
opcode,op1,rel,op2,OR,opcode,op1,rel,op2
Line 155:
CASE 7 case 7
LA R5,4 r5=4
ENDCASE end select</
=={{header|6502 Assembly}}==
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.
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:
<
CMP #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.
<
BEQ ;Branch on EQual - branch when the zero flag is set.
;The zero flag is set when the result of an operation is zero
Line 184:
;a subtraction produced a borrow and cleared if an addition/subtraction
;does not produce a carry/borrow. The carry flag also holds bits
;after shifts and rotates.</
In the following example, the branch will be taken if memory location Variable holds 200:
<
CMP Variable
BEQ #3 ;if equal, skip ahead 3 bytes...
CLC ;if unequal, continue executing instructions
ADC #1
STA OtherVariable ; ...to here.</
Because you don't have to perform a comparison to set the flags, you can perform very fast checks in iterative loops:
<
Loop: ...do something
DEX
BNE Loop</
This code will loop until X is zero.
Most assemblers will figure out the correct offset for you if you use a label in place of the offset after a branch instruction, as in the above example.
Line 203:
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.
<
dw foo-1 ;each is a label to a section of code that ends in an RTS
dw bar-1
Line 223:
; 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.</
=={{header|68000 Assembly}}==
Like [[6502 Assembly]], 68000 Assembly has several different condition states the CPU can use to branch. As is typical with assembly languages, branching code is less straightforward than on high-level languages. There is no "if" statement per se; the correct branch to use depends more so on the expression being evaluated.
Line 231:
===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.
<
CMP.B #0,D0 ;equals zero, so zero flag is set.
CMP.W #0,D0 ;doesn't equals zero, so zero flag is clear.</
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:
===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).
<
BNE goHere ;if that bit is 1, branch to "goHere"
BEQ goThere ;if that bit is 0, branch to "goThere"</
<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:
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.
<
BNE doNothing
ADD.L #7,D0
doNothing:
;rest of program</
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:
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.
<
DC.L foo,bar,baz,default ;case 0, case 1, case 2, case 3. (Case 0,1,2 are the "valid" cases.)
; D0 is the case selector variable (byte-sized)
Line 305:
default:
rts</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program condstr64.s */
Line 530:
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
<
INT i
Line 546:
FI
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Conditional_structures.png Screenshot from Atari 8-bit computer]
Line 560:
=={{header|Ada}}==
===if-then-else===
<
My_Var : Restricted;
Line 569:
else
-- do something
end if;</
===conditional expressions===
Ada 2012 introduces conditional expressions, which are allowed anywhere an expression is allowed (e.g.: in a numeric literal, aggregate, etc.). A conditional expression can either be an if expression or case expression. Conditional expressions must be surrounded by parentheses.
====if expression====
<
Op : Operation;
Result : Integer;
Line 585:
elsif Op = Divide then
A / B
);</
====case expressions====
Using the same example above, we assume that the <
<
Add => A + B,
Subtract => A - B,
Line 594:
Divide => A / B
);
</syntaxhighlight>
Note: some websites (particularly [https://www.radford.edu/nokie/classes/320/abe/operators.html#:~:text=if%20and%20case-,Examples%3A,1%2C%20others%20%3D%3E%200)%3B this one]) contain a different variant of a case expression (<syntaxhighlight lang
===case with a default alternative===
<
Today : Days;
Line 609:
when others =>
Accumulate_Sales;
end case;</
===case without a default===
Line 615:
I.e., the following code is syntactically incorrect:
<
when Monday =>
Compute_Starting_Balance;
Line 623:
Accumulate_Sales;
-- ignore Saturday and Sunday
end case;</
The syntactically correct version:
<
when Saturday | Sunday =>
null; -- don't do anything, if Today is Saturday or Sunday
Line 636:
when Tuesday .. Thursday =>
Accumulate_Sales;
end case;</
===select===
Line 643:
====Conditional Accept====
<
accept first_entry;
-- do something
Line 649:
-- do something
or terminate;
end select;</
====Conditional entry call====
A selective entry call provides a way to time-out an entry call.
Without the time-out the calling task will suspend until the entry call is accepted.
<
My_Task.Start;
or
delay Timeout_Period;
end select;</
The entry Start on the task My_Task will be called.
If My_Task accepts the entry call before the timer expires the timer is canceled. If the timeout expires before the entry call is accepted the entry call is canceled.
Line 664:
=={{header|Aikido}}==
===Conditional Expressions===
<
var x = loggedin ? sessionid : -1
</syntaxhighlight>
===if..elif..else===
<
if (value > 40) {
println ("OK")
Line 678:
println ("RETRY")
}
</syntaxhighlight>
===switch===
<
switch (arg) {
case "-d":
Line 707:
println ("RETRY")
}
</syntaxhighlight>
=={{header|Aime}}==
Line 713:
===If-elif-else===
<
// first condition is true...
} elif (c2) {
Line 721:
} else {
// none was true...
}</
=={{header|ALGOL 60}}==
Line 734:
'''if''' X=Y '''then''' K:=I
An example:
<
'IF' I<J 'THEN' OUTSTRING(1,'(' : I<J')')
Line 746:
OUTSTRING(1,'(' J=')');
OUTINTEGER(1,J)
'END'</
Algol 60 has also a switch structure:
declaration::= '''switch''' switch:=list_of labels
statement::= '''goto''' switch[expression]
An example:
<
...
'GOTO' TARGET(/J/);
L1: OUTSTRING(1,'('AA')');
L2: OUTSTRING(1,'('BB')');
L3: OUTSTRING(1,'('CC')');</
=={{header|ALGOL 68}}==
Line 762:
=={{header|ALGOL W}}==
<
integer a, b, c;
Line 793:
write( case c - a of ( "one", "two", "three", "four" ) )
end.</
{{out}}
<pre>
Line 810:
The second and third arguments should be blocks (aka anonymous functions or thunks).
<
if: condition then: {
// condition is true...
Line 816:
// condition is false...
}
</syntaxhighlight>
===IfTrue/IfFalse===
Line 822:
One can also send a message to the boolean objects true and false:
<
condition.ifTrue: { /* condition is true... */ } ifFalse: { /* condition is false... */ }
</syntaxhighlight>
=={{header|AmigaE}}==
'''IF-THEN-ELSE'''
<
-> if condition is true...
ELSEIF condition2
Line 834:
ELSE
-> if all other conditions are not true...
ENDIF</
or on one single line:
<syntaxhighlight lang
'''Ternary IF THEN ELSE'''
The IF-THEN-ELSE can be used like ternary operator (?: in C)
<
c := IF condition THEN 78 ELSE 19</
'''SELECT-CASE'''
<
CASE n1
-> code
Line 855:
DEFAULT
-> no one of the previous case...
ENDSELECT</
Another version allows for ranges:
<
CASE n1
-> code
Line 868:
DEFAULT
-> none of previous ones
ENDSELECT</
The biggest among n1, n2 and so on, must be not bigger than max_possible_value.
Line 874:
=={{header|Apex}}==
===if-then-else===
<
foo();
} else if (s == 'Bye World') {
Line 880:
} else {
deusEx();
}</
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
<
aMethod();
}</
<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:
<
aMethod();
}</
You will get a null pointer exception if obj is null.
===ternary===
<
===switch===
Line 899:
=={{header|AppleScript}}==
===if-then-else===
<
set i to 0
Line 908:
else
return "odd"
end if</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 1,063:
bx lr /* return */
</syntaxhighlight>
=={{header|Arturo}}==
===if?-else===
<
if? num=2 [
Line 1,075:
else [
print "something went wrong..."
]</
{{out}}
Line 1,083:
===case-when?===
<
case [num]
when? [<2] -> print [num ": it's less than 2"]
Line 1,090:
else -> print [num ": the number is too big"]
]
</syntaxhighlight>
{{out}}
Line 1,101:
=={{header|Astro}}==
<
foo()
elif x == 1:
Line 1,116:
_ => qux()
(a) ? b : c</
=={{header|AutoHotkey}}==
===if, else if, else===
<syntaxhighlight lang="autohotkey">x = 1
If x
MsgBox, x is %x%
Line 1,127:
MsgBox, x is %x%
Else
MsgBox, x is %x%</
===ternary if===
<syntaxhighlight lang="autohotkey">x = 2
y = 1
var := x > y ? 2 : 3
MsgBox, % var</
===while (looping if)===
<
MsgBox, %A_Index% is less than 3
}</
=={{header|AutoIt}}==
===If, ElseIf, Else===
<
statements
...
Line 1,152:
...
EndIf
</syntaxhighlight>
===Select Case===
<
Case <expression>
statement1
Line 1,165:
...]
EndSelect
</syntaxhighlight>
===Switch Case===
<
Case <value> [To <value>] [,<value> [To <value>] ...]
statement1
Line 1,178:
...]
EndSwitch
</syntaxhighlight>
--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 15:39, 13 November 2013 (UTC)
=={{header|Avail}}==
===If-Then-Else===
<
If someNumber > 5 then [Print: "Too high!";] else [Print: "Adequate amount.";];
Line 1,191:
else [score := 45;];
Unless char = ¢X then [Print: "character was not an x";];</
===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.
<
=={{header|AWK}}==
Conditionals in awk are modelled after C:
<
For a branch with more than a single statement, this needs braces:
<
if(i<0) {
i=0; j=1
} else {
i=42; j=2
}</
There is also the ternary conditional:
<
=={{header|Axe}}==
Line 1,215:
===Simple===
<
YEP()
End</
===Inverse If===
<
NOPE()
End</
===If-Else===
<
YEP()
Else
NOPE()
End</
Axe has no support for switch-like statements. If-ElseIf-Else structures are required to achieve the same goal.
===If-ElseIf-Else===
<
NOPE()
ElseIf 1=1
Line 1,240:
Else
NOPE()
End</
===If-InverseElseIf-Else===
<
NOPE()
Else!If 1=2
Line 1,249:
Else
NOPE()
End</
=={{header|Babel}}==
Line 1,255:
===Simple select===
<
"foo" "bar" 3 4 > sel <<
</syntaxhighlight>
Prints "foo" since '3 4 >' evaluates to false, which causes sel to remove "bar" from the stack.
Line 1,263:
===If-Then-Else===
<
{3 4 >}
{"foo"}
Line 1,269:
ifte
<<
</syntaxhighlight>
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:
===Conditional===
<
({3 4 >} {"Three is greater than four" }
{3 3 >} {"Three is greater than three"}
Line 1,282:
cond
<<
</syntaxhighlight>
Prints "Three is greater than two", as expected.
Line 1,292:
BASIC can use the if statement to perform conditional operations:
<
20 IF A% THEN PRINT "A IS TRUE"
30 WE CAN OF COURSE USE EXPRESSIONS
Line 1,298:
50 IF NOT(A%) THEN PRINT "A IS FALSE"
60 REM SOME VERSIONS OF BASIC PROVIDE AN ELSE KEYWORD
70 IF A% THEN PRINT "A IS TRUE" ELSE PRINT "A IS FALSE"</
Here are code snippets from a more modern variant that does not need line numbers:
Line 1,306:
Single line IF does not require END IF
<
IF x < 0 THEN doSomething ELSE doOtherThing</
Multi-line IF:
<
'do stuff
ELSE IF x = 0 THEN
Line 1,317:
ELSE
'do more stuff
END IF</
Like in [[#C|C]], any non-zero value is interpreted as True:
<
'the number is not 0
ELSE
'the number is 0
END IF</
===select case===
Line 1,332:
The condition in each case branch can be one or more constants or variables, a range or an expression.
<
CASE 1
'do stuff
Line 1,343:
CASE ELSE
'default case
END SELECT</
===Computed ON-GOTO===
Line 1,351:
or:
<
20 GOTO v * 100
99 STOP
Line 1,359:
210 STOP
300 PRINT "Cherry"
310 STOP</
===Conditional loops===
Line 1,365:
Some variants of basic support conditional loops:
<
20 L=0
30 WHILE L<5
Line 1,376:
100 PRINT L
110 L=L+1
120 UNTIL L>5</
==={{header|Applesoft BASIC}}===
Applesoft BASIC does not have ELSE, only the IF-THEN structure and computed ON-GOSUB and ON-GOTO
<
20 IF X THEN PRINT "X IS TRUE"
30 IF NOT X THEN PRINT "X IS FALSE"
Line 1,387:
100 PRINT "APPLE": RETURN
200 PRINT "BANANA": RETURN
300 PRINT "CHERRY"</
=={{header|BASIC256}}==
Line 1,429:
</pre>
I think this test shows that nested if statements parse as they do in c.
<syntaxhighlight lang="basic256">
for i = 0 to 1
for j = 0 to 1
Line 1,449:
next j
next i
</syntaxhighlight>
=={{header|Batch File}}==
IF syntax:
<
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
Line 1,468:
GEQ - greater than or equal
/I case insensitive string compares
</syntaxhighlight>
The ELSE clause must be on the same line as the command after the IF.
For example:
<
IF EXIST %filename% (
del %filename%
Line 1,477:
echo %filename% not found
)
</syntaxhighlight>
=={{header|BBC BASIC}}==
<
IF condition% THEN statements ELSE statements
Line 1,505:
REM ON ... PROC (ELSE clause is optional):
ON expression% PROCone, PROCtwo ... ELSE statements</
=={{header|beeswax}}==
Line 1,512:
The 4 conditional operators are:
<syntaxhighlight lang="beeswax">
' lstack top value == 0 ? skip next instruction : don’t skip next instruction.
" lstack top value > 0 ? skip next instruction : don’t skip next instruction.
K lstack top value == 2nd value ? skip next instruction : don’t skip next instruction.
L lstack top value > 2nd value ? skip next instruction : don’t skip next instruction.</
Example:
<
>`n > 0`d >`m > 0`d >Lp`m > n`;
>`m < n`;</
Example output:
<
i3
n > 0
Enter integer m:
i0
m = 0 and m < n</
=={{header|Befunge}}==
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.
<
> & |
> "0",@ zero</
'''#''' is the skip command.
It unconditionally skips one character, allowing a little flexibility in flow control.
<
> "X",@ non-zero</
=={{header|blz}}==
===if-else===
<
if i % 2 == 0
print("even")
Line 1,554:
print("odd")
end
</syntaxhighlight>
=={{header|Bori}}==
===if-elif-else===
<
if (i == 0)
return "zero";
Line 1,565:
else
return "even";
</syntaxhighlight>
=={{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:
<
IfElse ← {c‿T‿F: c◶F‿T@}
While ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´ # While 1‿{... to run forever
Line 1,579:
Select ← {(⊑𝕩)◶(1↓𝕩)@}
Switch ← {c←⊑𝕩 ⋄ m‿a←<˘⍉∘‿2⥊1↓𝕩 ⋄ (⊑a⊐C)◶m@}
Test ← {fn←{C‿A𝕊e:C◶A‿E}´𝕩⋄Fn@}</
The other method of branching is using function predicates, which can be used in any blocks for an if-else like conditional:
<
a<b ? a+↩1 ; # If
a<c ? c-↩1 ; # Else If
a-↩2 # Else
}</
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:
The following expression writes "That's what I thought." to your screen and evaluates to the expression "Right".
<
& put$"Strange, must check that Bracmat interpreter."
& 0
| put$"That's what I thought."
& Right</
=== switch-like branching ===
Line 1,612:
In the following example, the resulting expression is a single node containing "4".
<
: ( (<3|>5)
& put$"Not quite, must check that Bracmat interpreter."
Line 1,620:
& put$"That's what I thought."
)
</
=={{header|Brainf***}}==
Line 1,627:
Thus in the following sequence:
<syntaxhighlight lang
The . instruction will be skipped, while the following sequence
<syntaxhighlight lang
will result in an infinite loop. Finally, in the following sequence
<syntaxhighlight lang
The . instruction will be executed once.
Line 1,643:
Using the ''Choose'' command:
<
blsq ) 9 2.%{"Odd""Even"}ch
"Odd"
</syntaxhighlight>
Using the ''If'' command (produce next even number if odd):
<
blsq ) 9^^2.%{+.}if
10
blsq ) 10^^2.%{+.}if
10
</syntaxhighlight>
Using the ''IfThenElse'' command (produce next odd number if even or previous even number if odd):
<
blsq ) 10^^2.%{-.}\/{+.}\/ie
11
blsq ) 9^^2.%{-.}\/{+.}\/ie
8
</syntaxhighlight>
Emulating Switch-Case behaviour:
<
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Banana"Fi!!
"Like Bananas"
blsq ) {"Hate tomatos" "Like Bananas" "Hate Apples"}{"Tomato" "Banana" "Apple"}"Apple"Fi!!
"Hate Apples"
</syntaxhighlight>
=={{header|C}}==
Line 1,682:
===if-elseif-else===
<
{
// Some Task
Line 1,698:
{
// Some Task
}</
===Ternary===
<
int var = condition ? 1 : 2;</
===switch===
<
{
case 1:
Line 1,719:
// Some task
break;
}</
If fall through algorithms are required use the goto keyword.
<
{
case 1:
Line 1,737:
// Some task
break;
}</
=={{header|C++}}==
Line 1,752:
Selecting a type depending on a compile time condition
<
template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
Line 1,768:
long int, // in that case, we'll need a long int
int> // otherwise an int will do
::type myvar; // define variable myvar with that type</
=={{header|Clean}}==
Line 1,774:
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.
<
===case-of===
<
42 -> "Correct"
_ -> "Wrong" // default, matches anything</
===function alternatives===
<
answer _ = False</
===guards===
<
| x == 42 = True
| otherwise = False
Line 1,793:
n | n < 0 -> "Not even close"
42 -> "Correct"
// no default, could result in a run-time error</
=={{header|Clipper}}==
'''if-elseif-else-endif'''
<
SomeFunc1()
ELSEIF x == 2
Line 1,803:
ELSE
SomeFunc()
ENDIF</
'''do case'''
<
CASE x == 1
SomeFunc1()
Line 1,813:
OTHERWISE
SomeFunc()
ENDCASE</
=={{header|Clojure}}==
===if-then-else===
<
(if (= 1 2) :yes :no) ; returns :no
(if (= 1 2) :yes) ; returns nil</
===when===
Similar to if, but body in an implicit do block allowing multiple statements.
No facility for providing an else. <code>when</code> is defined as a macro.
<
(print "hello")
(println " world")
5) ; when x is logical true, prints "hello world" and returns 5; otherwise does nothing, returns nil</
===cond===
The cond macro takes a series of test/result pairs, evaluating each test until one resolves to logical true, then evaluates its result.
Returns nil if none of the tests yield true.
<
(= 1 2) :no) ; returns nil
(cond
(= 1 2) :no
(= 1 1) :yes) ; returns :yes</
Since non-nil objects are logical true, by convention the keyword :else is used to yield a default result.
<
(= 1 2) :no
:else :yes) ; returns :yes</
===condp===
Similar to cond, but useful when each test differs by only one variant.
<
4 :a ; cond equivalent would be (< 4 3) :a
3 :b
2 :c
1 :d) ; returns :c</
Optionally takes a final arg to be used as the default result if none of the tests match.
<
4 :a
3 :b
:no-match) ; returns :no-match</
===case===
{{Works with|Clojure|1.2}}
<
0 (println "0")
1 (println "1")
2 (println "2")) ; prints 2.</
=={{header|CMake}}==
<
if(num GREATER 100)
Line 1,875:
message("${num} is small.")
message("We might want a bigger number.")
endif()</
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:
=={{header|COBOL}}==
===if-then-else===
<
imperative-statement-1
else
Line 1,900:
imperative-statement-2
end-if
end-if</
===evaluate===
<
when 'good'
good-imperative-statement
Line 1,935:
when other
default-imperative-statement
end-evaluate</
=={{header|CoffeeScript}}==
Line 1,941:
===if-then-else===
<
if n == 1
console.log "one"
Line 1,948:
else
console.log "other"
</syntaxhighlight>
===switch===
<
switch n
Line 1,961:
else
console.log "other"
</syntaxhighlight>
===ternary expressions===
Line 1,967:
CoffeeScript is very expression-oriented, so you can assign the "result" of an if-then to a variable.
<
# alternate form
Line 1,973:
if condition
then "yup"
else "nope"</
=={{header|ColdFusion}}==
===if-elseif-else===
'''Compiler:''' [[ColdFusion]] any version
<
do something
<cfelseif x eq 4>
Line 1,984:
<cfelse>
do something else
</cfif></
===switch===
'''Compiler:''' [[ColdFusion]] any version
<
<cfcase value="1">
do something
Line 1,998:
do something
</cfdefaultcase>
</cfswitch></
=={{header|Comal}}==
===IF/THEN===
<
===IF/THEN/ELSE===
<
PRINT "True"
ELSE
PRINT "False"
ENDIF</
===IF/THEN/ELIF/ELSE===
<
PRINT "One"
ELIF choice=2 THEN
PRINT "Two"
ELSE
Print "None of the above"</
===CASE/WHEN===
<syntaxhighlight lang="comal">
CASE choice OF
WHEN 1
Line 2,029:
PRINT "Some other choice"
ENDCASE
</syntaxhighlight>
=={{header|Common Lisp}}==
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.
<
"That is the answer to life, the universe and everything"
"Try again") ; the else clause here is optional</
==== <code>when</code> and <code>unless</code> ====
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.
<
((and (> val 3) (< val 6)) (print "yes"))
((> val 99) (print "too far"))
(T (print "no way, man!")))</
=={{header|Computer/zero Assembly}}==
Line 2,065:
===if-elseif-else===
<
{
// Some Task
Line 2,081:
{
// Some Task
}</
===Ternary===
<
// if condition is true var will be set to 1, else false.
int var = condition ? 1 : 2;
</syntaxhighlight>
=={{header|D}}==
:''See [[Conditional Structures#C|C]], sans the preprocessor.''
<
enum int i = 5;
Line 2,141:
// default: // Forbidden in final switches.
}
}</
=={{header|Dao}}==
===If Elif Else===
<
if( a == 1 ){
io.writeln( 'a == 1' )
Line 2,152:
}else{
io.writeln( 'a is neither 1 nor 3' )
}</
===Switch Case===
<
switch( a ){
case 0: io.writeln( 'case 0' )
Line 2,161:
case 3, 4, 5: io.writeln( 'case 3,4,5' )
default: io.writeln( 'default' )
}</
=={{header|Delphi}}==
Line 2,169:
=={{header|Deluge}}==
<
sVar = "good";
} else if (input.Field == "Bye World") {
Line 2,175:
} else {
sVar = "neutral";
}</
=={{header|DM}}==
===if-elseif-else===
<
// Do thing, DM uses indentation for control flow.
Line 2,190:
else
// Do thing
</syntaxhighlight>
===Ternary===
<
var/x = condition ? 1 : 2
</syntaxhighlight>
===Switch===
<
if (0)
// Do thing if zero
Line 2,212:
else
// Fallback if nothing was matched.
</syntaxhighlight>
=={{header|Dragon}}==
===if-then-else===
<
{
add()
Line 2,225:
{
both()
}</
=={{header|DWScript}}==
Line 2,232:
=={{header|Déjà Vu}}==
<
pass
elseif b:
pass
else: # c, maybe?
pass</
=={{header|E}}==
Line 2,243:
===if-then-else===
<
println("okay")
} else if (!okay) {
Line 2,249:
} else {
println("not my day")
}</
The pick/2 message of booleans provides a value-based conditional:
<
It can therefore be used to construct a Smalltalk-style conditional:
<
println("okay")
}, fn {
println("not okay")
})()</
All of the above conditionals are expressions and have a usable return value.
Line 2,269:
E's "switch" allows pattern matching.
<
def value := switch (expression) {
Line 2,275:
match [`*`, [a, b]] { a * b }
match [op, _] { throw(`unknown operator: $op`) }
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">i = random 10
if i mod 2 = 0
print i & " is divisible by 2"
Line 2,285:
else
print i & " is not divisible by 2 or 3"
.</
=={{header|Efene}}==
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
<
show_if_with_parenthesis = fn (Num) {
if (Num == 1) {
Line 2,352:
show_switch_with_parenthesis(random.uniform(3))
show_switch_without_parenthesis(random.uniform(3))
}</
=={{header|Ela}}==
Line 2,358:
===if-then-else===
<
===Guards===
<
| else = x</
===Pattern matching===
<
force [] = []</
===match expression===
<
x::xs = x :: force xs
[] = []</
=={{header|Erlang}}==
Line 2,389:
case expressions take an expression and match it to a pattern with optional guards.
<
{N,M} when N > M -> M;
{N,M} when N < M -> N;
_ -> equal
end.</
===if===
Line 2,400:
Guards must evaluate to true or false so true is the catch-all clause.
<
if
N > M -> M;
N < M -> N;
true -> equal
end.</
===Function Clauses===
Line 2,411:
Functions can have multiple clauses tested in order.
<
test({N,M}) when N < M -> N;
test(_) -> equal.</
=={{header|F_Sharp|F#}}==
<
printfn "%s" (if 3<2 then "3 is less than 2" else "3 is not less than 2")
</syntaxhighlight>
{{out}}
<pre>
Line 2,431:
===?===
? is for when you don't need branching, but only need to select between two different values.
<
t 1 2 ? ! returns 1
</syntaxhighlight>
===if===
<
===cond===
<
===case===
<
===when===
<
===unless===
<
=={{header|FALSE}}==
<syntaxhighlight lang
Because there is no "else", you need to stash the condition if you want the same effect:
<
or
<
=={{header|Fancy}}==
Line 2,461:
===if:then:===
<
"x < y!" println # will only execute this block if x < y
}
</syntaxhighlight>
===if:then:else::===
<
"x < y!" println # will only execute this block if x < y
} else: {
"x not < y!" println
}
</syntaxhighlight>
===if_true:===
<
"x < y!" println # will only execute this block if x < y
}
</syntaxhighlight>
===if_false: / if_nil:===
<
"x not < y!" println # will only execute this block if x >= y
}
</syntaxhighlight>
===if_true:else:===
<
"x < y!" println
} else: {
"x >= y!" println
}
</syntaxhighlight>
===if_false:else:===
<
"x >= y!"
} else: {
"x < y!" println
}
</syntaxhighlight>
===if:===
<
===unless:===
<
=={{header|Forth}}==
===IF-ELSE===
<
( condition ) IF ( true statements ) ELSE ( false statements ) THEN</
example:
<
===CASE-OF===
<
( integer ) OF ( statements ) ENDOF
( integer ) OF ( statements ) ENDOF
( default instructions )
ENDCASE</
example: a simple CASE selection
<
CASE
0 OF ." Zero!" ENDOF
1 OF ." One!" ENDOF
." Some other number!"
ENDCASE ;</
===Execution vector===
To obtain the efficiency of a C switch statement for enumerations, one needs to construct one's own execution vector.
<
CREATE ( default-xt [count-xts] count -- ) DUP , 0 DO , LOOP ,
DOES> ( u -- ) TUCK @ MIN 1+ CELLS + @ EXECUTE ;
Line 2,551:
8 digit \ eight
34 digit \ Out of range!</
===Execution Vector 2===
This method was used by the late Jim Kalihan and Dr. Julian Nobel
<
\ lookup execution token and compile
Line 2,575:
===IF-THEN-ELSE===
ANSI FORTRAN 77 or later has an IF-THEN-ELSE structure:
<
q = q + a**2
else if ( a .ge. 0.0 ) then
Line 2,581:
else
q = q - a
end if</
===SELECT-CASE===
ISO Fortran 90 or later has a SELECT-CASE structure:
<
case (21:) ! matches all integers greater than 20
q = q + i**2
Line 2,592:
case default ! matches all other integers (negative in this particular case)
q = q - I
end select</
===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.
<
where (edge_type(1:n,1:m) == center)
anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5
Line 2,626:
elsewhere ! sink/source, does not change
anew(1:n,1:m) = a(1:n,1:m)
end where</
=={{header|FreeBASIC}}==
===IF-ELSEIF-ELSE-END IF===
<
If a = 1 Then
sub1
Line 2,637:
Else
sub3
End If</
===SELECT-CASE===
<
Select Case a
Case 1
Line 2,648:
Case Else
sub3
End Select</
===IFF===
<
Dim i As Integer = IIf(b, 1, 2)</
===ON-GOTO===
<
On a Goto label1, label2</
===IF-GOTO (deprecated)===
<
If b Goto label</
===ON-GOSUB (legacy dialects only)===
<
On a Gosub label1, label2</
===#IF-#ELSEIF-#ELSE-#ENDIF (preprocessor)===
<
#IF (WORDSIZE = 16)
' Do some some 16 bit stuff
Line 2,674:
#ELSE
#ERROR WORDSIZE must be set to 16 or 32
#ENDIF</
===#IFDEF (preprocessor)===
<
#IFDEF _DEBUG
' Special statements for debugging
#ENDIF</
===#IFNDEF (preprocessor)===
<
#DEFINE _DEBUG
#ENDIF</
=={{header|friendly interactive shell}}==
===if-then-else===
<
if test $var = 'Hello World'
echo 'Welcome.'
Line 2,696:
else
echo 'Huh?'
end</
===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 az
echo The word is "az".
Line 2,711:
case '*'
echo Neither begins with a or ends with z.
end</
=={{header|Futhark}}==
Line 2,718:
Futhark supports branching with a syntax common to most functional languages.
<
if <condition> then <truebranch> else <falsebranch>
</syntaxhighlight>
=={{header|GAP}}==
=== if-then-else ===
<
<statements>
elif <condition> then
Line 2,730:
else
<statements>
fi;</
=={{header|Go}}==
Line 2,736:
===If===
Simplest usage is,
<
statements
}</
The braces are required, even around a single statement.
<
statements
} else {
other
statements
}</
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,
<
statements
} else if booleanExpression2 {
otherStatements
}
</syntaxhighlight>
If allows a statement to be included ahead of the condition. This is commonly a short variable declaration, as in,
<
DoPos(x)
} else {
DoNeg(x)
}</
In this case the scope of x is limited to if statement.
===Switch===
Simple usage is,
<
case booleanExpression1:
statements
Line 2,773:
resort
statements
}</
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,
<
case value1:
statements
Line 2,783:
other
statements
}</
As shown, multiple values can be listed for a single case clause.
Since go is statically typed, the types of value1, 2, 3, and 4 must match the type of the expression.
As with if, a local statement such as a short variable declaration can precede the expression. If there is no expression, the statement is still marked by a semicolon:
<
case x == "cheese":
statements
Line 2,794:
other
statements
}</
Also, as with if, the scope of x is limited to the switch statement.
Line 2,800:
An interesting example:
<
case booleanExpression1:
default:
Line 2,809:
other
statements
}</
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.
<
switch {
case true:
Line 2,819:
}
fmt.Println("I want out!")
}</
Labels provide the desired capability. The following prints "I'm off!"
<
switch {
case true:
Line 2,827:
}
}
fmt.Println("I'm off!")</
=={{header|Harbour}}==
'''if-elseif-else-endif'''
<
SomeFunc1()
ELSEIF x == 2
Line 2,837:
ELSE
SomeFunc()
ENDIF</
'''do case'''
<
CASE x == 1
SomeFunc1()
Line 2,847:
OTHERWISE
SomeFunc()
ENDCASE</
'''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.
<
CASE 1
SomeFunc1()
Line 2,860:
OTHERWISE
SomeFunc()
ENDSWITCH</
=={{header|Haskell}}==
===if-then-else===
<
1
else x * fac (x - 1)</
===Guards===
<
| x>0 = x * fac (x-1)</
===Pattern matching===
<
fac x = x * fac (x-1)</
===case statement===
<
_ -> x * fac (x-1)</
=={{header|HicEst}}==
<
IF( a >= b ) THEN
Line 2,890:
ELSE
WRITE(StatusBar) a, b, some_string
ENDIF</
=={{header|HPPPL}}==
=== IF ===
Note that X has to be a number; else a runtime error occurs.
<
// do if X is not 0
ELSE
// do if X is 0
END;</
=== CASE ===
<
IF X == 1 THEN
// do stuff if X equals 1
Line 2,913:
DEFAULT
// do other stuff
END;</
=={{header|i}}==
<
software {
a = 3
Line 2,927:
print("a = ", a)
end
}</
=={{header|Icon}} and {{header|Unicon}}==
Line 2,933:
===if-then-else===
The control structure evaluates expr1 if expr0 succeeds and expr2 if it fails.
<
expr1
else
expr2</
===case-of===
The first successful selection expression will select and evaluate the specific case.
<
expr1 : expr2
expr3 : expr4
default: expr5
}</
Note that expr1 and expr3 are expressions and not constants and it is possible to write expressions such as:
<
f(x) | g(x) : expr2
s(x) & t(x) : expr4
default: expr5
}</
===Compound expressions (blocks)===
In the examples below, multiple expressions can be grouped as in:
<syntaxhighlight lang="icon">{
expr1
expr2
expr3
}</
Which is equivalent to this:
<syntaxhighlight lang
For example the following, which will write 4, looks strange but is valid:
<
The value of a compound expression is the value of the last expression in the block.
===Alternation===
Alternation of expressions yields a value for the first succeeding expression.
<
===Conjunction===
Conjunctions yeild the value of the final expression provided all the previous expressions succeed.
<
Alternately, conjunction can be written thus:
<
===Conjunction, yielding a different result===
The alternate form of conjunction can be modified to produce a different result (other than the last)
<
For example:
<
Yields the value of expr2 if all of the expressions succeed.
<br>A more complicated example showing non-constant expressions:
<
Note: if expr0 yields a value of type 'procedure' or 'string' the appropriate procedure (or operator) is invoked.
Line 2,986:
Basic if/then:
<
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:
<
... some code here ...
endif [else begin
... some other code here ...
endelse]</
===case===
<
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[else: <command-else>]
endcase</
(Or replace any of the commands with {begin..end} pairs)
Line 3,008:
===switch===
<
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[else: <command-else>]
endswitch</
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:
===on_error===
<syntaxhighlight lang
Will resume execution at label when an error is encountered. <tt>on_ioerror</tt> is similar but for IO errors.
Line 3,024:
=={{header|Inform 7}}==
===if-then-else===
<
if N is 1, say "one.";
otherwise say "not one.";
Line 3,037:
[short and long forms can be negated with "unless"]
unless N is 1, say "not one."</
===switch===
<
-- 1: say "one.";
-- 2: say "two.";
-- otherwise: say "not one or two.";</
===if-then-else in text===
<
say "[unless N is odd]even.[end if]";</
===other branching text substitutions===
Text that may be printed multiple times can also use sequential and random branching:
<
say "[one of]red[or]blue[or]green[at random].";
Line 3,058:
[only appears once]
say "[first time]Hello world![only]";</
===rulebook approach===
Conditional logic may also be expressed in the form of a rulebook, with conditions on each rule:
<
Number handling is a number based rulebook with default success.
Line 3,075:
follow the number handling rules for 2;
follow the number handling rules for 4;
follow the number handling rules for 5.</
=={{header|Isabelle}}==
<
imports Main
begin
Line 3,099:
lemma "recurse n = 0" by(induction n) simp+
end</
=={{header|J}}==
Line 3,106:
=={{header|Java}}==
===if-then-else===
<
{
foo();
Line 3,115:
{
deusEx();
}</
Java also supports [[wp:Short-circuit_evaluation|short-circuit evaluation]]. So in a conditional like this:
<
aMethod();
}</
<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:
<
aMethod();
}</
You will get a null pointer exception if obj is null.
===ternary===
<
===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).
<
case 'a':
foo();
Line 3,139:
default:
foobar();
}</
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:
<
foo();
}else if(c == 'b'){
Line 3,150:
}else{
foobar();
}</
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:
===if-then-else===
<
foo();
} else if( s == "Bye World" ) {
Line 3,163:
} else {
deusEx();
}</
===switch===
<
case 1:
one();
Line 3,181:
default:
everythingElse();
}</
===conditional (ternary) operator (?:)===
<
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.
<
'use strict';
var varHead = lst.length ? lst[0] : null;
Line 3,198:
) : []
) : [];
}</
=={{header|JCL}}==
Line 3,211:
</pre>
The syntax of COND parameter of the EXEC statement is :
<
relop is a relational opeator : EQ NE GT LT GE LE (= ¬= < > <= >=) </
It is a condition to bypass a job step, and it can be translateted into :
<
Example:
<
<pre>
if 0 ne STEP3.rc then skip step STEP6
Line 3,224:
</pre>
The conditions can be multiple :
<
Means:
<
Example:
<
<pre>
if 4 le STEP1.rc or 8 le STEP3.rc then skip step STEP6
Line 3,239:
===if-then-else===
<
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{% if loop.last %}.{% else %},{% endif %}
{%- endfor %}""").render())
</syntaxhighlight>
===ternary expressions===
<
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{{ "." if loop.last else "," }}
{%- endfor %}""").render())
</syntaxhighlight>
===short-circuit evaluation===
<
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}{{ loop.last and "." or "," }}
{%- endfor %}""").render())
</syntaxhighlight>
=={{header|jq}}==
jq's main conditional construct is:<
# all JSON values are truthy except for false and null;
# if cond evaluates to nothing (i.e., produces an empty stream), then the entire if-then-else-end expression also produces an empty stream.
The general pattern allows one or more "elif _ then _" clauses:
<syntaxhighlight lang="jq">
if cond then f elif cond1 then f1 .... else g end
</syntaxhighlight>
For example:<
if empty then 2 else 3 end # produces no value
if 1 then 2 else 3 end # produces 2
if [false, false] then 2 else 3 end # produces 2
if (true, true) then 2 else 3 end # produces a stream: 2, 2
</
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:<
exp
| if . == true then "true"
Line 3,285:
elif type == "string" then .
else error("unexpected value: \(.)")
end</
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:
Note: this documentation is mostly copied from the Julia 0.6.0 documentation at: https://docs.julialang.org/en/stable/manual/control-flow/#man-conditional-evaluation-1
<h3>Conditional Evaluation</h3>
<syntaxhighlight lang="julia">
function test(x, y)
if x < y
Line 3,310:
julia> test(1, 1)
x is equal to y
</syntaxhighlight>
<p>
The elseif and else blocks are optional, and as many elseif blocks as desired can be used. The condition expressions in the if-elseif-else construct are evaluated until the first one evaluates to true, after which the associated block is evaluated, and no further condition expressions or blocks are evaluated.
</p><p>
The so-called "ternary operator", ?:, is closely related to the if-elseif-else syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:
</p><
a ? b : c
</syntaxhighlight>
<p>
The expression a, before the ?, is a condition expression, and the ternary operation evaluates the expression b, before the :, if the condition a is true or the expression c, after the :, if it is false. To facilitate chaining, the operator associates from right to left.
Line 3,332:
=={{header|Kabap}}==
Kabap supports the '''if''' statement and a range of standard comparators. Truthiness is considered anything not "0" or 0.
<syntaxhighlight lang="kabap">
if 1;
$result = "Execute";
Line 3,388:
}
</syntaxhighlight>
=={{header|Keg}}==
Keg supports if statements like this:
<
Usually the ending proprotions may be omitted:
<
Also Keg supports (though not intentionally) a form of short-circuit evaluation:
<
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 3,427:
}
println("$i is $t")
}</
Sample input/output (program invoked without arguments):
{{out}}
Line 3,447:
=={{header|Lambdatalk}}==
<
{if true then yes else no}
-> yes
Line 3,465:
{switch 0}
-> 0 is zero
</syntaxhighlight>
=={{header|langur}}==
Line 3,474:
===if expressions===
If expressions are scoped per section.
<
# ... and that a decoupling assignment returns a Boolean...
Line 3,487:
val .y = 70
...
}</
Prior to langur 0.10, you would use parentheses around the declared variable names (.alias, .name).
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).
<
===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.
<
===given expressions===
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.
<
case true: ...
# all are true
Line 3,515:
case _, null, true: ...
# .y == null and .z == true
}</
As of 0.7, complex test expressions are evaluated once, then compared against conditions.
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".
<
case 7 <, 14, 21: ...
# 7 < .x and .y == 14 and 21 != .z
Line 3,535:
default: ...
}</
===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.
<
case true:
# implicit fallthrough
Line 3,545:
# no fallthrough
default: 1
}</
===explicit fallthrough from anywhere===
A fallthrough statement is allowed anywhere within a given block, not just at the end.
<
case true:
if .y > 100 {
Line 3,557:
}
case false: ...
}</
===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).
<
true: ... ; # all are equal to true
_, >= .z: ...; # .y >= .z
... ) # default</
=={{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.
<
; branch if (result < 0 || result == 0 || result > 0)
; ^ this is always true
Line 3,577:
; or any combination of these condition codes, e.g.
BRnz ; branch if (result <= 0)</
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.
<
LD R1, x ; get x
LD R2, y ; get y
Line 3,597:
taken .stringz "Branch Taken!"
nottaken .stringz "Branch Not Taken!"
.end</
=={{header|LIL}}==
LIL sports '''if''' with an optional code block for else conditions.
<
if {$a > 10} {print "again"} {print "code evaluated on false"}</
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:
{{works with|Lisaac|0.13.1}}
===if-then-else===
<
n := 3;
Line 3,624:
} else {
IO.put_string "n is none of the above\n";
};</
<
(n = 2).if_false { "n is not 2\n".print; };</
===when===
<
n := 3;
Line 3,640:
.when 4 then {
"n is 4\n".print;
};</
There is no "else" or "otherwise" method.
If the values of the when-methods are overlapped, the related blocks will be evaluated ... they are not mutually exclusive.
Line 3,646:
=={{header|Little}}==
<
// if-then-else
Line 3,679:
default:
puts("is neither");
}</
=={{header|Logo}}==
<
ifelse emptyp :list [print [empty]] [print :list]</
[[UCB Logo]] and its descendants have also case:
<
output case :letter [ [[a e i o u] "true] [else "false] ]
end
show vowel? "e
show vowel? "x</
{{out}}
<
false</
Logo also provides TEST which is local to a procedure:
<
test :arg1 = :arg2
iftrue [print [Arguments are equal]]
iffalse [print [Arguments are not equal]]
end</
=={{header|LSE}}==
==={{header|SI..ALORS..SINON..FIN SI}}===
<
AFFICHER [4X, 'A ET B = .VRAI.',/]
SINON
Line 3,712:
SINON
AFFICHER [4X, 'A ET QUE B = .FAUX.',/]
FIN SI</
==={{header|EVALUER}}===
<
QUAND 0
AFFICHER [4X,'QUAND X=0',/]
Line 3,724:
QUAND AUTRE
AFFICHER [4X,'QUAND X est autre, X=',U,/] X
FIN EVALUER</
==={{header|SELON..ALLER EN..}}===
<
1 AFFICHER [8X,U,X,/] '0 VACHES'
2 AFFICHER [8X,U,/] '1 MOUTONS'
Line 3,734:
10 AFFICHER [U,/] 'Vous avez choisi VACHES!'
15 TERMINER
20 AFFICHER [U,/] 'Vous avez choisi MOUTONS!'</
==={{header|SI..ALORS..SINON..IS}}===
<
==={{header|SELON..DANS..SINON..FIN}}===
<
=={{header|LSE64}}==
The simple conditionals take single words rather than blocks of statements, as in most other languages.
<
f : " false" ,t
true if t
false ifnot f
true ifelse t f</
Cascading conditionals are constructed using duplicate definitions and "then", yielding a syntax reminiscent of functional language [[Pattern Matching]].
<
onetwo : dup 2 = then " Two" ,t
onetwo : dup 1 = then " One" ,t</
Short-circuit operators "&&" and "||" are used for complex conditionals.
<
=={{header|Lua}}==
<syntaxhighlight lang="lua">
--if-then-elseif-then-else
if a then
Line 3,791:
}
cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively</
=={{header|Luna}}==
===if-then-else===
<
''(see: [https://github.com/luna/luna/issues/125#issuecomment-365683922 github/luna #125])''
===case-of===
<
...
def asText: case self of:
JSONString t: t
other: throw "JSON.asText: not a text"</
''(see: [https://github.com/luna/luna/blob/77b1d974cb07528e9f195dd47e177dd497560da1/stdlib/Std/src/Base.luna#L1047-L1050 Std.JSON])''
Line 3,810:
=={{header|M2000 Interpreter}}==
===If Then Else.if Else===
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Read a
Line 3,848:
CheckIt 0
CheckIt -100
</syntaxhighlight>
===IF() and IF$() - Ternary===
One expression evaluated only. We can use If$() to use string expressions
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Read x
Line 3,869:
Checkit 3, 20
</syntaxhighlight>
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">
Module Checkit {
def a
Line 3,887:
}
Checkit
</syntaxhighlight>
===Select Case===
We can use string, and three types of cases (all of them in one case), >1000, 10 to 40, 400
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Read a
Line 3,933:
CheckIt -500
</syntaxhighlight>
===Conditional loops===
<syntaxhighlight lang="m2000 interpreter">
x=10
While x>0 {
Line 3,958:
Until x=10
</syntaxhighlight>
===On Goto, On Gosub===
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
For i=1 to 10 {
Line 3,992:
CheckIt
</syntaxhighlight>
===If Then line No /label===
Line numbers are optional and can be in any order, but from start in current block, and if not found then replaced with exit, until search can't continue (at modules/function bounds, we can't jump out of a module or function).
<syntaxhighlight lang="m2000 interpreter">
a$="123"
if a$ ~ "12*" then 1000
Line 4,004:
1000 Print "ok final"
Goto alfa
</syntaxhighlight>
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:
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">
Module Checkit {
Rem : Dim beta(10) ' remove Rem to get error when call beta() without Gosub
Line 4,031:
Checkit
</syntaxhighlight>
=={{header|Make}}==
An if condition using pure make (no gmake extensions)
<
C=0
Line 4,046:
false:
@echo "was false."</
Using it
<
> was false.
make -f do.mk if C=1
> was true.</
With out using recursion but letting make continue with non-failed
targets even when some of the targets failed (-k)
<
if: true false
Line 4,067:
false:
@expr $(C) >/dev/null && exit 1 || exit 0
@echo "was false."</
Invoking it. Note the use of -k which allows make to evaluate subsequent
targets even when a previous non-related target failed.
<
was true.
*** Error code 1
|make -f do.mk -s -k C=0
*** Error code 1
was false.</
Using gmake
<
B=
Line 4,090:
do:
@echo $(A) .. $(B)</
Using it
<
1 .. true
|gmake -f if.mk A=0
0 .. false</
=={{header|Maple}}==
Line 4,103:
=== Conditional statements ===
Example syntax for conditional statements:
<
res := x;
else
res := -x;
end if;</
Example syntax for conditional statements with else-if:
<
res := y;
elif y = 0 then
Line 4,116:
else
res := sqrt(x^2+y^2);
end if;</
=== Conditional functions ===
Line 4,141:
===If statements===
Example:
<
disp 'x==1';
elseif x > 1
Line 4,147:
else
disp 'x<1';
end</
===Switch statements===
Example:
<
case 1
disp 'Hello';
Line 4,157:
otherwise
disp 'Skynet Active';
end</
=={{header|Maxima}}==
<
=={{header|MAXScript}}==
===if===
<
(
print "one"
Line 4,175:
(
print "Neither one or two"
)</
===case===
'''Form one'''
<
(
1: (print "one")
2: (print "two")
default: (print "Neither one or two")
)</
'''Form two'''
<
(
(x == 1): (print "one")
(x == 2): (print "two")
default: (print "Neither one or two")
)</
=={{header|MBS}}==
<
x:=0;
IF x = 1 THEN
Line 4,201:
ELSE
! Do something else
ENDIF;</
=={{header|MDL}}==
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.
<
(<==? .X 2> <PRINC "two">)
(T <PRINC "something else">)></
===AND and OR===
Line 4,219:
These short-circuiting boolean functions can also be used as simple conditionals.
<
<AND <L? .X 0> <SET X <- .X>>>
;"Print a message unless the quiet flag is set"
<OR .QUIET? <PRINC "Finished">></
=={{header|Metafont}}==
<
% do something
elseif conditionB:
Line 4,234:
else:
% do this
fi;</
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
<
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:
=={{header|min}}==
{{works with|min|0.19.6}}
<
; evaluate second quotation.
; Otherwise, evaluate the third.
Line 4,258:
((3 <) ("Smaller than 3" puts!)) ; quotation if the first quotation
((true) ("Exactly 3" puts!)) ; evaluates to true. Otherwise, move
) case ; on to the next one.</
=={{header|MiniScript}}==
MiniScript supports if/else-if/else, with arbitrary number of else-if sections when in block form:
<
if x < 10 then
print "small"
Line 4,272:
else
print "just right"
end if</
It also supports single-line if or if/else statements (though no else-if sections are permitted in this case):
<
if x < 50 then print "small" else print "big"</
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.
<
print "checking smallness"
return x < 40
Line 4,291:
end function
isSmall(10) or isBig(100)</
{{out}}
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.
===If/Else===
<
nop ;branch delay slot</
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:
<
lw $t3,($t4)
nop ;load delay slot
BEQ $t0,$t1,Label
nop ;branch delay slot</
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:
<
subiu $t0,1 ;this finishes at the same time the jumpback occurs.</
MIPS also comes with greater than/less than constructs built-in.
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!''
<
NOP
BLT $t7,$t3,label ;branch if $t7 < $t3, treating both as signed
NOP</
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:
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.
<
;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.)
Line 4,358:
baz:
;code goes here
jr ra</
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:
Conditional jumps are done by four instructions, comparing the register X with zero:
<syntaxhighlight lang="text">x=0 XX
x#0 XX
x>=0 XX
x<0 XX</
'''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:
=={{header|Modula-2}}==
===if-then-else===
<
InOut.WriteString('One')
ELSIF i = 2 THEN
Line 4,382:
ELSE
InOut.WriteString('Other')
END;</
===Case===
<
1 : InOut.WriteString('One')
| 2 : InOut.WriteString('Two')
Line 4,391:
ELSE
InOut.WriteString('Other')
END</
=={{header|Modula-3}}==
===if-then-else===
<
Bar();
ELSE
Baz();
END;</
<
Bar();
ELSIF Foo = "bar" THEN
Line 4,409:
ELSE
Zeepf();
END;</
===Case===
<
| 1 => IO.Put("One\n");
| 2 => IO.Put("Two\n");
Line 4,418:
ELSE
IO.Put("Something\n");
END;</
===Type-case===
<tt>TYPECASE</tt> is used on reference types to perform different operations, depending on what it is a reference to.
<
| NULL => IO.Put("Null\n");
| CHAR => IO.Put("Char\n");
Line 4,427:
ELSE
IO.Put("Something\n");
END;</
=={{header|Monicelli}}==
Monicelli has a single conditional structure that covers both if/then/else and switch/case
<
che cosè var? # switch var
minore di 0: # case var < 0
Line 4,440:
...
e velocità di esecuzione
</syntaxhighlight>
=={{header|Morfa}}==
===if-then-else===
<
if(s == "Hello World")
{
Line 4,455:
baz();
}
</syntaxhighlight>
Morfa supports [[wp:Short-circuit_evaluation|short-circuit evaluation]], so <tt>obj.foo()</tt> won't be executed if <tt>obj</tt> is null:
<
if(obj isnt null and obj.foo())
doSomething();
</syntaxhighlight>
===ternary===
<
var t = if(s == "Hello World") foo() else bar();
</syntaxhighlight>
===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.
<
switch (num)
{
Line 4,481:
result = "a lot";
}
</syntaxhighlight>
=={{header|MUMPS}}==
===If / I and ELSE / E===
<syntaxhighlight lang
<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:
<
ELSE DO SOMETHING</
It isn't clear whether $TEST is changed or not, because the function SUBROUTINE might change the value of $TEST by using a timeout or an IF command.
It is better to explicitly set the $TEST special variable using IF 1 for example:
<syntaxhighlight lang="mumps">
IF T DO SUBROUTINE IF 1
ELSE DO SOMETHING</
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">
IF T DO
. DO SUBROUTINE
ELSE DO SOMETHING</
Line 4,509:
===$Select / $S===
<
<p>The $Select statement contains couplets separated by commas, which each consist of a conditional test, followed by a colon, and what to return if that condition is true.
The first part of the couplet must be a truth value. Since only zero is interpreted a truth value of false, any nonzero numbers when interpreted as a truth value will be considered to be true. Typically the number 1 is used as an explicitly true condition and is placed in the final couplet. If no conditions are true, the program's error processing is invoked. The very first condition that is true is the result of the expression. In the example, the value will always be "Unequal" as it is always true, and the rest of the $SELECT will never be used.</p>
===(command postconditional i.e. colon/:===
<
GOTO:ReallyGo LABEL
QUIT:LoopDone
WRITE:NotLastInSet ","</
<p>Most commands can take a "postconditional", which is a colon and some conditional statement immediately after the command followed by the command separator (space) and the usual arguments of the command. The command is executed only if the conditional statement evaluates to true.</p>
<p>The exceptions are FOR, IF, and ELSE.
Line 4,536:
=={{header|Nanoquery}}==
===if-then-else===
<
foo()
else if x = 1
Line 4,544:
else
boz()
end</
=={{header|Nemerle}}==
===if-else===
<tt>if (cond) <then> else <this>;</tt> is an expression in Nemerle, requiring both keywords (<tt>if</tt> and <tt>else</tt>) to be valid. <tt>when</tt> and <tt>unless</tt> are macros for which <this> = null. <tt>cond</tt> must be an expression that evaluates to a bool (true|false), other types aren't automatically assigned truth or falsehood as in some languages.
<
when (stock.price < buy_order) stock.Buy();
unless (text < "") Write(text);</
===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].
<
{
|1 => "x is one"
|x when (x < 5) => "x is less than five"
|_ => "x is at least five"
}</
=={{header|NetRexx}}==
===IF-THEN-ELSE===
<
if logicalCondition then conditionWasTrue()
else conditionWasFalse()
Line 4,597:
conditionsWereFalse()
...
end</
===SELECT===
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.
<
select
when logicalCondition1 then condition1()
Line 4,621:
catch ex1 = NoOtherwiseException
ex1.printStackTrace()
end</
===SELECT-CASE===
<
select case cc
when 'A' then say 'the case is A'
when 'B' then say 'the case is B'
otherwise say 'selection not recognized'
end</
'''Note:''' This is functionally equivalent to:
<
when cc == 'A' then ...
when cc == 'B' then ...
...</
===SELECT Optional Features===
Line 4,648:
<tt>PROTECT</tt> is used for program concurrency & synchonization in multi-threaded programs.
<
when 'A' then do
say 'the case is A'
Line 4,667:
say 'selection done'
say 'TTFN'
end sl</
=={{header|newLISP}}==
===if===
'''Interpreter:''' [[newLISP]] v.9.0
<
(if (= x 1) (println "is 1"))</
A third expression can be used as an else.
<
(if (= x 1) (println "is 1") (println "not 1"))</
=={{header|Nim}}==
===if-then-else===
<
foo()
elif x == 1:
Line 4,687:
baz()
else:
boz()</
===case-of===
<
of 0:
foo()
Line 4,698:
baz()
else: # All cases must be covered
boz()</
=={{header|Objeck}}==
===if-else===
<
a := GetValue();
if(a < 5) {
Line 4,713:
"equal to 5"->PrintLine();
};
</syntaxhighlight>
===select===
<
a := GetValue();
select(a) {
Line 4,731:
}
};
</syntaxhighlight>
=={{header|Object Pascal}}==
Line 4,744:
===if-then-else===
<
if condition then
1 (* evaluate something *)
else
2 (* evaluate something *)</
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:
<
(); (* evaluate things for side effects *)
5
Line 4,760:
(); (* evaluate things for side effects *)
42
end</
===match-with===
<
| 0 -> () (* evaluate something *)
| 1 -> () (* evaluate something *)
| n when n mod 2 = 0 -> () (* evaluate something *)
| _ -> () (* evaluate something *)</
The first <tt>|</tt> is optional, and usually omitted.
Line 4,777:
=={{header|Octave}}==
'''if-then-elseif-else'''
<
% body
endif
Line 4,793:
else
% otherwise body
endif</
'''switch'''
<
case label1
% code for label1
Line 4,803:
otherwise
% none of the previous
endswitch</
''Labels'' can be numeric or string, or cells to group several possibilities:
<
case 1
disp("it is 1");
Line 4,814:
otherwise
disp("unknown!");
endswitch</
=={{header|Oforth}}==
Line 4,820:
Conditional structures are :
<
aBoolean ifFalse: [ ... ]
aObject ifNull: [ ... ]
aObject ifNotNull: [ ... ]
aObject ifZero: [ ... ]</
Each conditional structure consume the object on the top of the stack.
Each conditional structure can be followed by a else block
<syntaxhighlight lang
Example :
<
self isPositive
ifTrue: [ self ==0 ifTrue: [ 0 ] else: [ 1 ] ]
else: [ -1 ] ;</
=={{header|Ol}}==
if-then, the simplest conditional primitive.
<
(if (= (* 2 2) 4) (print "if-then: equal"))
(if (= (* 2 2) 6) (print "if-then: non equal"))
; ==> if-then: equal
</syntaxhighlight>
if-then-else, the full conditional 'if' primitive.
<
(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-then-else: equal
; ==> if-then-else: i don't know
</syntaxhighlight>
unless, the opposite for 'if'.
<
(unless (= (* 2 2) 4) (print "unless: non equal"))
(unless (= (* 2 2) 6) (print "unless: i don't know"))
Line 4,863:
; ==> unless: equal
; ==> unless: i don't know
</syntaxhighlight>
case, the sequence of comparing values.
<
(case (* 2 2)
(3
Line 4,877:
(print "case: i don't know")))
; ==> case: 4
</syntaxhighlight>
additionally, case can select vectors with variables filling
<
(case (vector 'selector 1 2 3)
(['case1 x y]
Line 4,889:
(print "case: i don't know")))
; ==> tuple-case: selector 1, 2, 3
</syntaxhighlight>
cond, the sequnce of comparators.
<
(cond
((= (* 2 2) 4)
Line 4,901:
(print "cond: i don't know")))
; ==> cond: equal
</syntaxhighlight>
case-lambda, selecting the lambda based on arguments count.
<
(define smart (case-lambda
((x)
Line 4,915:
(smart 1 2) ; ==> 1, 2, -
(smart 1 2 3) ; ==> 1, 2, 3
</syntaxhighlight>
=={{header|ooRexx}}==
Line 4,924:
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,
<
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
<
With this form, the second conditional expression is only evaluated if the first expression is true.
===IF THEN --- IF THEN/ELSE===
<syntaxhighlight lang="oorexx">
if y then x=6 /* Y must be either 0 or 1 */
Line 4,959:
else nop
else if z<0 then z=-y
</syntaxhighlight>
===SELECT WHEN===
<syntaxhighlight lang="oorexx">
/*the WHEN conditional operators are the same as */
/*the IF conditional operators. */
Line 4,977:
/*were satisfiied, a SYNTAX condition is raised (error).*/
end
</syntaxhighlight>
===SELECT WHEN/OTHERWISE===
<syntaxhighlight lang="oorexx">
select
when a=='angel' then many='host'
Line 4,994:
exit 13
end
</syntaxhighlight>
=={{header|OxygenBasic}}==
<
if a then b=c else b=d
Line 5,019:
end select
</syntaxhighlight>
=={{header|Oz}}==
===if-then-else===
<
if {IsEven X} then
{Show even}
Line 5,031:
{Show 'should not happen'}
end
end</
===if-then-else as a ternary operator===
<
if X > Y then X else Y end
end</
===case statement===
<
case X of 0 then 1
[] _ then X * {Fac X-1}
end
end</
=={{header|PARI/GP}}==
GP uses a simple <code>if</code> statement:
<syntaxhighlight lang
and short-circuit <code>&&</code> and <code>||</code> (which can be abbreviated <code>&</code> and <code>|</code> if desired).
Line 5,055:
===if-then-else===
<
procedure1
ELSE
Line 5,077:
procedure3;
procedure4
END;</
=== case ===
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.
<
1,4,9: { executed if i is 1, 4 or 9 }
DoSomething;
Line 5,095:
else
DoYetAnotherThing;
end;</
Given the variable "X" as a char the following is valid:
<
'A' : statement ;
'B' : statement ;
Line 5,105:
else
Statement ;
end;</
=={{header|Perl}}==
Line 5,112:
===if/else===
<
do_something;
}</
<
do_something if $expression;</
<
do_something;
}
else {
do_fallback;
}</
<
do_something;
}
Line 5,134:
else {
do_fallback;
}</
===unless===
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.
<
===logical operators===
<
<
<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:
{{works with|Perl|5.10}}
<
given ($input) {
when (0) { print 'input == 0'; }
Line 5,169:
when (/rats/) { print 'input matches rats'; }
default { do_fallback; }
}</
=={{header|Phix}}==
{{libheader|Phix/basics}}
===if===
<!--<
<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>
Line 5,185:
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
There is no limit to the number of elsif clauses, including 0. The else clause is also optional,
Line 5,192:
===iff===
<!--<
<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;">)
<!--</
In an iff() expression, only one of true_expr or false_expr will be evaluated, not both.
Line 5,202:
first if statement, and in the second the conditions are evaluated at compile-time and code is only
emitted for one of the branches.
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">DEBUG<span style="color: #0000FF;">=<span style="color: #004600;">false</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">DEBUG</span> <span style="color: #008080;">then</span>
Line 5,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: #008080;">end</span> <span style="color: #008080;">if
<!--</
===switch===
<!--<
<span style="color: #008080;">switch</span> <span style="color: #000000;">v</span> <span style="color: #000080;font-style:italic;">/*with fallthrough*/</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">:</span>
Line 5,228:
<span style="color: #000080;font-style:italic;">-- do something</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch
<!--</
By default there is no fallthough on switch clauses, however you can add(/uncomment) a directive, and you can
Line 5,244:
use them, also have some conditional guards for cross-platform support
<
#ilASM{
[32]
Line 5,266:
syscall
[]
}</
=={{header|PHL}}==
Line 5,272:
If-else:
<
if (a == 5) {
doSomething();
Line 5,279:
} else {
error();
}</
=={{header|PHP}}==
Line 5,287:
'''Interpreter''': [[PHP]] 3.x, 4.x, 5.x
<
$foo = 3;
Line 5,308:
}
?></
===switch===
Line 5,314:
'''Interpreter''': [[PHP]] 3.x & 4.x & 5.x
<
switch ($i)
Line 5,331:
}
?></
===See Also===
Line 5,348:
Here are examples of each of these constructs.
<
N = 10,
Line 5,393:
% condition in function head
test_func(N) = "less than 14", N < 14 => true.
test_func(_N) = "not less than 14" => true. </
{{out}}
Line 5,405:
=={{header|PicoLisp}}==
===Two-way conditions===
<
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
Line 5,413:
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(and-more) )</
One-way conditions
<
(then-do-this) # Then execute tall following expressions
(and-more) )
Line 5,421:
(unless (condition) # If the condition evaluates to NIL
(then-do-this) # Then execute all following expressions
(and-more) )</
===Four-way condition===
<
(expression-both) # Then execute this expression
(expression-first) # Otherwise this for the first
(expression-second) # or this the second condition.
(expression-none) # If both are NIL, all following expressions
(and-more) )</
===Multiple conditions===
<
((condition1) # If this condition evaluates to non-NIL
(expression 1) # Execute these expression(s)
Line 5,450:
(NIL # If none evaluated to NIL
(expression 1) # Execute these expression(s)
(more 1) )</
===Selection===
<
(value1 # If it is equal to, or member of, 'value1'
(do-this1) # Execute these expression(s)
Line 5,461:
(do-that2) )
(T # Else execute final expression(s)
(do-something-else) ) )</
=={{header|PL/I}}==
===if-then-else===
<
if condition_exp then
Line 5,478:
else do;
list_of_statements;
end;</
So a cascading form can be derived from:
<
statement_1;
else if condition_exp2 then
Line 5,501:
else do;
list_of_statements;
end;</
=== case ===
Line 5,507:
==== select - format 1 ====
<
when (1,4,9)
do;
Line 5,522:
statement_s;
end;
end;</
==== select - format 2 ====
<
when (i = 4)
do;
Line 5,545:
statement_s;
end;
end;</
Notes:
Line 5,555:
=={{header|PL/M}}==
IF-THEN-ELSE:
<
IF COND THEN STATEMENT1; ELSE STATEMENT2;
Line 5,562:
ELSE IF CONB2 THEN STATEMENT2;
ELSE IF CONB3 THEN STATEMENT3;
ELSE STATEMENTX;</
DO-CASE:
<
/* DEPENDING ON WHETHER EXPR EVALUATES TO 0, 1, ... */
/* EXPR MUST BE IN RANGE OR THE PROGRAM WILL JUMP TO HYPERSPACE */
Line 5,572:
STATEMENT1;
...
END;</
=={{header|Pop11}}==
Line 5,578:
The simplest conditional is:
<
;;; Action
endif;</
Two way conditional looks like:
<
;;; Action1
else
;;; Alternative action
endif;</
One can do multiway choice using elseif clause
<
;;; Action1
elseif condition2 then
Line 5,602:
else
;;; Alternative action
endif;</
Instead of if keyword one can use unless keyword.
<
has the same meaning as
<
One can also use elseunless keword.
<
;;; Action1
elseunless condition2 then
Line 5,620:
endif;
;;; Action2
endif;</
has the same meaning as
<
;;; Action1
elseif not(condition2) then
;;; Action2
endif;</
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:
Pop11 conditional is an expression:
<
assigns sign of x to sign_x.
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).
<
case .isstring then printf('A1');
notcase .isinteger then printf('A2');
Line 5,647:
case > 4 andcase < 15 then printf('A4');
else printf('A5');
endswitchon;</
There is also multiway goto statement and conditional control transfers, we explain them together with other control transfers
Line 5,654:
Pop11 also has preprocessor allowing conditional compilation:
<
/* Variant 1 */
#_ELSEIF condition2
Line 5,660:
#_ELSE
/* Variant 3 */
#_ENDIF</
condition1 and condition2 are arbitrary Pop11 expressions (they have access to all previously compiled code).
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>ifelse</tt>" operator expects two procedures and executes the one or the other depending on the value of the boolean. I.e. this:
<
will render either the string "yeah" or "nope" depending on whether <tt>a</tt> is less than 5 or not.
Line 5,680:
=={{header|PowerShell}}==
===If, ElseIf, Else===
<
if (condition) {
# ...
Line 5,699:
} else {
# ...
}</
===Switch===
<
switch ($var) {
1 { "Value was 1" }
Line 5,730:
"\d+" { "Line started with a number" }
"\s+" { "Line started with whitespace" }
}</
=={{header|Prolog}}==
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:
<
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.)
<
fact(bar).
fact(baz).
go :- fact(booger).
go :- fact(bar).</
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.
<
( X = foo
; X = bar
Line 5,756:
go :-
( fact(booger)
; fact(bar) ).</
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:
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):
<
( X = bar -> write('You got me!'), nl
; write(X), write(' is not right!'), nl, fail ).
Line 5,768:
go :-
( fact(booger)
; fact(bar) ).</
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:
{{works with|PureBasic|4.41}}
===If, Elseif, Else===
<
Debug "a = 0"
Line 5,784:
Debug "a < 0"
EndIf</
===Select===
<
Select Variable
Line 5,801:
Default
Debug "Variable = something else..."
EndSelect</
===CompilerIf===
Compiler conditional structures works like normal conditional structures, except they are evaluated at compile time, and thus have to use constant expressions. Any defined constant can be used, these examples uses built-in constants.
<syntaxhighlight lang="purebasic">
CompilerIf #PB_Compiler_OS = #PB_OS_Linux And #PB_Compiler_Processor = #PB_Processor_x86
Debug "Compiled on x86 Linux"
Line 5,811:
Debug "Compiled on something else"
CompilerEndIf
</syntaxhighlight>
===CompilerSelect===
<syntaxhighlight lang="purebasic">
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_Linux
Line 5,825:
Debug "Compiled on something else"
CompilerEndIf
</syntaxhighlight>
=={{header|Python}}==
===if-then-else===
<
foo()
elif x == 1:
Line 5,837:
baz()
else:
boz()</
===ternary expressions===
'''Interpreter:''' [[Python]] 2.5
<syntaxhighlight lang
Example:
<
>>> print 'got it' if secret=='foo' else 'try again'
'got it'</
'''Note:''' this syntax is valid as an expression, the clauses cannot constain statements. The foregoing example is equivalent to:
<
>>> result = 'got it' if secret=='foo' else 'try again'
>>> print result
'got it'</
===Function dispatch dictionary===
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.
<
dispatcher[0]=foo # Not foo(): we bind the dictionary entry to the function's object,
# NOT to the results returned by an invocation of the function
Line 5,870:
# or with no "default" case:
if x in dispatcher:
results=dispatcher[x]()</
<
dispatcher = {
0: foo,
Line 5,879:
}
# ...
results = dispatcher.get(x, boz)()</
<
# (it's up to the reader to decide how "pythonic" this is or isn't)
results = {
Line 5,887:
1: bar,
2: baz,
}.get(x, boz)()</
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:
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
Print "QB64/Qbasic conditional structures"
Line 6,021:
End Sub
</syntaxhighlight>
Line 6,097:
===if===
Like most languages, R has an if statement as well as if-then-else:
<
if(x == 0) print("foo")
x <- 1
if(x == 0) print("foo")
if(x == 0) print("foo") else print("bar")</
{{out}}
<pre>> if(x == 0) print("foo")
Line 6,111:
===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.
<
switch(x, print("Print if x == 1"), print("Print if x == 2"))</
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.
<
switch(x, print("Print if x == 1"), print("Print if x == 2"))
x <- 2.7
switch(x, print("Print if x == 1"), print("Print if x == 2 or if there is rounding to 2"))</
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.
<
switch(x, mat = 0, match = 10, other = 100, 1000)
x <- "ma"
switch(x, mat = 0, match = 10, other = 100, 1000)
x <- "foo"
switch(x, mat = 0, match = 10, other = 100, 1000)</
{{out}}
<pre>> switch(x, print("Print if x == 1"), print("Print if x == 2"))
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:
<
ifelse(data == 1, "Yes", "No")</
{{out}}
<pre>> ifelse(data == 1, "Yes", "No")
Line 6,155:
===[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 (< x 10)
"small"
"big")
</syntaxhighlight>
===[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
<
(when (< x 10)
(define y (* x 10))
(printf "small\n"))
</syntaxhighlight>
===[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:
<
(printf "x is ~a\n"
(cond [(< x 1) "tiny"]
Line 6,179:
[(< x 100000000) "huge"]
[else "gigantic"]))
</syntaxhighlight>
===[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
<
(case x
[(1) "one"]
Line 6,192:
[(5 7 9) "odd"]
[else "something else"])
</syntaxhighlight>
===etc===
Line 6,204:
</li><li> <tt>unless</tt> no longer permits <tt>elsif</tt> or <tt>else</tt> blocks.
</li><li> If the block of an <tt>if</tt>, <tt>elsif</tt>, or <tt>unless</tt> has a nonzero arity, the value of the conditional expression is used as an argument to the block:
<syntaxhighlight lang="raku"
say "You won $prize.";
}</
If an <tt>else</tt> block has a nonzero arity, it receives the value of the condition tested by the last <tt>if</tt> or <tt>elsif</tt>. </li></ul>
===given/when===
Switch structures are done by topicalization and by smartmatching in Raku. They are somewhat orthogonal, you can use a <tt>given</tt> block without <tt>when</tt>, and vice versa. But the typical use is:
<syntaxhighlight lang="raku"
when 'yes' { return }
when 'no' { next }
default { say "Please answer either yes or no." }
}</
<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>)
Line 6,223:
===Ternary operator===
The [[wp:ternary operator|ternary operator]] looks like this:
<syntaxhighlight lang="raku"
===Other short-circuiting operators===
Line 6,231:
===If-Either-Case-Switch===
If the result is true, the block! will be evaluated. If false nothing happens.
<
ten is bigger</
===EITHER===
If the result is true the first block! will be evaluated.
If false the second block! will be evaluated.
<
Three larger</
===CASE===
The block! following the first true condition is evaluated.
<
case [
n < 10 [print "small number"]
Line 6,261:
medium number
large number
none of these</
===SWITCH===
<
"a" [print "string"]
23 [print "integer"]
Line 6,280:
]
no match</
=={{header|Retro}}==
===choose, if, and -if===
<
condition [ false statements ] -if
condition [ true statements ] [ false statements ] choose</
These forms can be used interactively, or inside function definitions.
===when===
<
#1 [ ( if quote evaluates to true ) ] case
#2 [ ( if quote evaluates to true ) ] case
#3 [ ( if quote evaluates to true ) ] case
drop ( default action ) ;</
=={{header|REXX}}==
===IF--THEN, IF--THEN--ELSE===
<
if t**2>u then x=y /*simple IF with THEN & ELSE. */
Line 6,316:
substr(abc,4,1)=='~' then if z=0 then call punt
else nop /*NOP pairs up IF*/
else if z<0 then z=-y /*alignment helps*/</
===SELECT--WHEN===
<
/*the IF conditional operators. */
select
Line 6,342:
when a=='wolf' then many='pack'
otherwise many='?'
end /*2nd select*/ /* [↑] uses OTHERWISE as a catch-all.*/</
===SELECT--WHEN/OTHERWISE===
<
when g=='angel' then many='host'
when g=='ass' | g=='donkey' then many='pace'
Line 6,358:
say
exit 13
end /*select*/</
=={{header|Rhope}}==
{{works with|Rhope|alpha 1}}
===if-then-else===
<
|:
Do Something[]
:||:
Do Something Else[]
:|</
=={{header|Ring}}==
'''if-but-else-ok'''
<
SomeFunc1()
But x == 2
Line 6,378:
Else
SomeFunc()
Ok</
'''Switch'''
<
On 1
SomeFunc1()
Line 6,388:
Other
SomeFunc()
Off</
=={{header|RLaB}}==
Line 6,394:
=== if ===
Block of instructions following the ''if'' command has to be always enclosed in curly brackets.
<syntaxhighlight lang="rlab">
if (x==1)
{
// do something
}
</syntaxhighlight>
=== if-else ===
Line 6,405:
Consider an example:
<syntaxhighlight lang="rlab">
if (x==1)
{
Line 6,414:
y = sin(const.pi*(1-x)) / (1-x);
}
</syntaxhighlight>
<syntaxhighlight lang="rlab">
if (x==1)
{
Line 6,429:
y = rand();
}}
</syntaxhighlight>
=={{header|Ruby}}==
Line 6,435:
=={{header|Run BASIC}}==
<
'
' > Greater Than
Line 6,514:
print "color unknown"
end select</
=={{header|Rust}}==
Line 6,520:
====Conditional compilation====
Rust supports conditional compilation via the `cfg` annotation.
<
#[cfg(target_os = "linux")]
fn running_linux() {
Line 6,541:
))]
fn highly_specific_function() {}
</syntaxhighlight>
Conditional compilation may also be achieved via the `cfg!` macro.
<
if cfg!(target_os = "linux") {
// Do something
}
}</
====Generics (static dispatch)====
By default, generics in Rust are monomorphized, so no vtable lookups at runtime are necessary.
<
fn print_type(&self);
}
Line 6,578:
prints_type_of_args(&'a', &2.0);
prints_type_of_args(&'a', &'b');
}</
===Runtime===
====If-statement====
<
do_stuff();
} else if some_other_conditional {
Line 6,602:
// Do something with x_coord and y_coord
}
}</
====Match statement====
Match statements are essentially more powerful switch statements
<
match p {
Some(Point { x: 0, y: 0 }) => println!("Point is on origin"),
Line 6,615:
None => println!("We didn't get a point"),
}
}</
====Generics (dynamic dispatch)====
Generics may also be accomplished via dynamic dispatch, so the actual code that is run is determined at compile time.
Using the same trait defined in the static dispatch section:
<
arg1.print_type();
arg2.print_type();
Line 6,627:
prints_args_dynamic(&'a', &2.0);
prints_args_dynamic(&6.3,&'c');
}</
=={{header|Sather}}==
<
-- CODE
elsif EXPR then
Line 6,637:
else
-- CODE
end;</
EXPR must evaluate to BOOL (true or false); <code>elsif</code> and <code>else</code> are optional.
<
when EXPRL then
-- CODE
Line 6,648:
else
-- CODE
end;</
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:
=={{header|Scala}}==
{{libheader|Scala}}
<
today match {
Line 6,664:
Accumulate_Sales
case _ => {}
}</
=={{header|Scheme}}==
Line 6,671:
===Primitive===
====if====
<syntaxhighlight lang="text">(if <test> <consequent> <alternate>)</
<syntaxhighlight lang="text">(if <test> <consequent>)</
Example:
<
(if (> 1 2)
"yes"
Line 6,682:
(if (> 1 2)
(- 1 2)))
(newline)</
{{out}}
<pre>no
Line 6,689:
===Derived===
====cond====
<syntaxhighlight lang="text">(cond <clause1> <clause2> ...)</
Example:
<
(cond ((> 1 2) "greater")
((< 1 2) "less")))
Line 6,699:
((< 1 1) "less")
(else "equal")))
(newline)</
{{out}}
<pre>less
Line 6,705:
====case====
<syntaxhighlight lang="text">(case <key> <clause1> <clause2> ...)</
Example:
<
(case (* 2 3)
((2 3 5 7) "prime")
Line 6,717:
((w y) "semivowel")
(else "consonant")))
(newline)</
{{out}}
<pre>composite
Line 6,742:
There can be single or multiple statements.
An if-statement can have multiple elsif parts.
<
statement
end if;
Line 6,764:
else
statement3;
end if;</
=== case ===
<
when {1, 4, 9}: # Executed if i is 1, 4 or 9
statement1;
Line 6,776:
otherwise:
statement4;
end case;</
=={{header|SIMPOL}}==
===if-else if-else===
<
foo()
else if x == 2
Line 6,786:
else
foobar()
end if</
===ternary if function===
<
=={{header|Simula}}==
Line 6,799:
'''if''' X=Y '''then''' K:=I
An example:
<
INTEGER i,j;
i:=1; j:=2;
Line 6,817:
END;
OutImage
END</
Simula 67 has also a switch structure:
declaration::= '''switch''' switch:=list_of labels
statement::= '''goto''' switch[expression]
An example:
<
INTEGER i,j;
SWITCH target:=L1,L2,L3;
Line 6,832:
L3: OutText("CC");
OutImage
END</
=={{header|Slate}}==
===ifTrue/ifFalse===
<
balance > 0
ifTrue: [inform: 'still sitting pretty!'.]
ifFalse: [inform: 'No money till payday!'.].</
===caseOf:otherwise:===
<
[ | byte1 byte2 byte3 digit1 digit2|
[c in isAtEnd] whileFalse:
Line 6,857:
} otherwise: [c out nextPut: byte1].
].
].</
===whileTrue:/whileFalse:===
<
=={{header|Smalltalk}}==
Line 6,877:
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 ¹ (the receiver is the following examples is a boolean, which get the alternative code pieces as argument):
<
balance > 0
ifTrue: [Transcript cr; show: 'still sitting pretty!'.]
Line 6,889:
ifFalse:[ self gotoHappyHour ]
ifTrue:[ self noDrinksToday ].
</syntaxhighlight>
You can also use them as the ternary operator
<
Or get the alternatives from somewhere else (for example, passed as parameter)
<
trueAction := [ ... do something ].
falseAction := [ ... do something else ...].
...
abs := x > 0 ifTrue:trueAction ifFalse:falseAction. "3)"</
Note ¹ 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:
===Switch Case===
<
x := 1.
value :=
Line 6,916:
[3]->['three']
}
otherwise:['none of them'].</
=={{header|SNOBOL4}}==
SNOBOL4 has no structured programming features, but the two constructs in question could be easily emulated with FAILURE/SUCCESS and indirect jumps
<
* "if-then-else"
if A "true" :s(goTrue)f(goFalse)
Line 6,934:
default output = "A is neither FALSE nor TRUE"
esac
end</
=={{header|SNUSP}}==
<
\==non zero==/</
'''?''' is the only conditional operator. It skips one character if the current cell is zero.
Line 6,953:
If statement:
<
if odd % 2 != 0 {
print("odd");
}</
If-else statement:
<
if odd % 2 != 0 {
print("odd");
} else {
print("even");
}</
If and if-else statements can be chained:
<
if nodiv3 % 3 == 0 {
print("divisible by 3");
Line 6,976:
} else {
print("gives 2 remainder");
}</
There's no "switch-case" statement in Sparkling yet, but it's work in progress.
Line 6,983:
{{works with|MS SQL|2005}}
===Conditional Expression===
<
declare @n int
Line 6,991:
--If/ElseIf expression
set @n=5
print case when @n=3 then 'Three' when @n=4 then 'Four' else 'Other' end</
===If/Else===
<
set @n=123
if @n=123
Line 7,002:
ELSE
if @n=124 print 'one two four'
else print 'other'</
=={{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.
<
00000000000000110000000000000000 Test
01110000000000000000000000000000 14 to CI</
=={{header|Stata}}==
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.
<
set obs 4
gen a = cond(mod(_n, 2)==1, "A", "B")
Line 7,024:
| A |
| B |
+---+</
=== 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.
<
sca n = `0'
sca p = 1
Line 7,062:
isprime `=10^12-11'
999999999989 is prime.</
=== 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.
<
set obs 100
count
100
count if mod(_n, 3)==0
33</
=== 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.
<
if (n<5) return(n==2 | n==3)
else if (mod(n, 2)==0) return(0)
Line 7,089:
isprime(10^12-11)
1</
=== ternary operator in Mata ===
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.
<
return(n<2 ? n : fib(n-1)+fib(n-2))
}
fib(10)
55</
=={{header|Swahili}}==
===if-else if-else (kama-au-sivyo)===
<
andika("statement")
} au (kweli /* condition */) {
Line 7,112:
} sivyo {
andika("statement")
}</
=={{header|Tailspin}}==
Tailspin has only one true conditional structure, a set of matchers. Each templates (sort of a function that takes one input value and emits zero or more outputs) has a set of matchers. If it only has matchers, they are invoked. If the templates has a
block, the matchers are invoked by sending to them (by "-> #"). The matchers can also be used as a looping structure by sending values back to be matched (also by "-> #").
<
templates foo
when <=0> do 'zero' -> !OUT::write
Line 7,126:
otherwise 'odd' -> !OUT::write
end foo
</syntaxhighlight>
=={{header|Tcl}}==
===if-then-else===
<
puts "foo is three"
} elseif {$foo == 4} {
Line 7,137:
} else {
puts "foo is neither three nor four"
}</
or (using the ternary operator of expressions)
<
===switch===
<
3 {puts "foo is three"}
4 {puts "foo is four"}
default {puts "foo is something else"}
}</
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:
===If Statement===
<
println(a);</
===If Else Statement===
<
println(a);
} else {
println(b);
}</
===Unless Statement===
<
println(b);
} else {
println(a);
}</
===Switch Statement===
<
case 10:
case 11:
Line 7,179:
default:
println(b);
}</
=={{header|TI-83 BASIC}}==
Line 7,186:
'''Basic form'''
<br> with only one statement for the true part:
<
statement</
or in one line
<syntaxhighlight lang
'''If-Then form'''
<
Then
statements
End</
'''If-Then-Else form'''
<
Then
statements
Else
statements
End</
=={{header|Toka}}==
Line 7,210:
( condition ) ( quote ) ifTrue
<
100 200 = [ ." True\n" ] ifTrue</
===ifFalse===
( condition ) ( quote ) ifFalse
<
100 200 = [ ." True\n" ] ifFalse</
===ifTrueFalse===
( condition ) ( true quote ) ( false quote ) ifTrueFalse
<
100 200 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse</
=={{header|TorqueScript}}==
Line 7,229:
===if-then-else===
<
if(%num == 1)
{
Line 7,255:
{
deusEx();
}</
===switch===
<
switch(%num)
{
Line 7,287:
default:
somethingElse();
}</
===conditional (ternary) operator (?:)===
<
=={{header|Trith}}==
===branch===
<
===when===
<
===unless===
<
=={{header|True BASIC}}==
<
! IF-ELSEIF-ELSE-END IF
! SELECT-CASE
Line 7,338:
ON expresión Gosub label1, label2 ELSE label3
</syntaxhighlight>
=={{header|TUSCRIPT}}==
===IF ELSEIF ELSE ENDIF===
<
$$ MODE TUSCRIPT
Line 7,353:
---> do something
ENDIF
</syntaxhighlight>
===SELECT CASE DEFAULT ENDSELECT===
<
$$ MODE TUSCRIPT
Line 7,370:
---> do something
ENDSELECT
</syntaxhighlight>
=={{header|TXR}}==
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:
<
@(choose :shortest x)
@x:@y
Line 7,389:
@(or)
@x+@y
@(end)</
Suppose the input is something which can match all three patterns in different ways:
Line 7,408:
For instance:
<
@x:y@
@z<-@w
Line 7,415:
We have a match: (x, y, z, w) = (@x, @y, @z, @w).
@(end)
@(end)</
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:
<
@# after the rightmost occurence of : such that the same piece
@# of text also occurs at the start of the line preceded by -->
Line 7,427:
@(and)
-->@x@/.*/
@(end)</
<pre>$ echo "-->asdfhjig:asdf" | txr -B weird.txr -
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.
<
==== Else and elif ====
Line 7,449:
There are optional <code>elif</code> (else if) and <code>else</code> clauses.
<
echo '4 is greater than or equal to 6'
elif test 4 -lt 6; then
Line 7,455:
else
echo '4 compares not to 6'
fi</
==== Switch conditionals ====
Line 7,461:
The Unix shell provides support for multibranch switch conditional constructs using the case statement:
<
choicea)
foo
Line 7,468:
bar
;;
esac</
==== Conditional branching using operators ====
Line 7,474:
One can also use <code>&&</code> and <code>||</code> as conditional structures; see [[short-circuit evaluation#UNIX Shell]].
<
test 4 -ge 6 || echo '4 is not greater than or equal to 6'</
==== Conditional loops ====
Line 7,481:
The Unix shell also supports conditional loops:
<
l=1
while [ l -le 5 ]; do
Line 7,491:
until [ l -eq 5 ]; do
echo $l
done</
==={{header|C Shell}}===
The single-line <code>if</code> syntax is <code>if (''expression'') ''simple-command''</code>.
<
if ({ grep -q ^root: /etc/passwd }) echo 'passwd has root'</
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.
<
echo '4 is greater than or equal to 6'
else if (4 < 6) then
Line 7,507:
else
echo '4 compares not to 6'
endif</
=={{header|Unison}}==
<
factorial x =
if x == 0 then 1
else
x * fac (Nat.drop x 1)</
=={{header|V}}==
===ifThenElse===
<
['is true' puts]
['is false' puts]
ifte
=is true</
===ifThen===
<
['is true' puts]
if
=is true</
===When===
<
[1 =] [1 *]
[2 =] [10 *]
Line 7,539:
] when
=300</
===Choice===
<
1 2
choice
Line 7,551:
choice
=2</
=={{header|VBA}}==
===If Else End If===
<syntaxhighlight lang="vb">
Sub C_S_If()
Dim A$, B$
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."
End Sub</
===If ElseIf Else End If===
<
Dim A$, B$
Line 7,598:
Debug.Print A & " < " & B
End If
End Sub</
===Select Case===
<
'With Strings
Dim A$, C&
Line 7,651:
Debug.Print "C >= 20"
End Select
End Sub</
===Inline IF===
<
Dim myName
myName = 2
Line 7,659:
'return : Justin
End Sub
</syntaxhighlight>
===Switch===
<
Dim myName
myName = 2
Line 7,667:
'return : Justin
End Sub
</syntaxhighlight>
=={{header|VBScript}}==
===if-then-else===
Block form:
<
statement
End If
Line 7,686:
statement
End If
</syntaxhighlight>
Line form:
<
If condition Then statement Else statement</
===select-case===
<
Case Value1: statement
Case Value2: statement
Line 7,710:
Case Else
statements
End Select</
=={{header|Verbexx}}==
<
// -------------------------------------------------------------------------------------
Line 7,782:
n = 0 @CASE results: n == 0(1)
n = 1 @CASE results: n == 1(2c)
n = 2 @CASE results: else</
=={{header|Verilog}}==
===if-else===
<syntaxhighlight lang="verilog">
if( expr_booleana ) command1;
else command2;
</syntaxhighlight>
===case===
<syntaxhighlight lang="verilog">
case( expr_booleana )
valor1: command1;
Line 7,800:
default: commandN;
endcase
</syntaxhighlight>
Line 7,806:
===if-then-else===
====Block form====
<
statement
End If
Line 7,825:
Else
statement
End If</
====Line form====
<
If condition Then statement Else statement</
===select-case===
<
Case Value1: statement
Case Value2: statement
Line 7,852:
statements
End Select
</syntaxhighlight>
===inline if-then-else===
<
Example:
<
Debug.Print IIf(myName = 1, "John", "Jack")
'return : "Jack")</
===inline switch===
<
Example:
<
Debug.Print Switch(myName = 1, "James", myName = 2, "Jacob", myName = 3, "Jeremy")
'return : "Jacob"</
=={{header|Visual Basic .NET}}==
Line 7,871:
===if-then-else===
''Basic''
<
If a = b Then
Line 7,877:
Else
result = "failed"
End If</
''Condensed''
<
If a = b Then result = "passed" Else result = "failed"
Line 7,892:
Else
result = "failed"
End If</
===if-then-elseif===
<
If a = b Then
Line 7,903:
Else
result = "impossible"
End If</
===select-case-else===
<
Select Case a
Line 7,914:
Case Else
result = "impossible"
End Select</
===inline-conditional===
<
...
Line 7,923:
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</
===generic-inline-conditional===
{{works with|Visual Basic .NET|8.0}}
<
...
Line 7,937:
...
Dim result As String = IIf2("pants" = "glasses", "passed", "failed") ' type is inferred</
===generic-inline-conditional===
'''Language Version:''' 9.0+
<
=={{header|Vlang}}==
Line 7,948:
===If===
Simplest usage is,
<
statements
}</
The braces are required, even around a single statement.
<
statements
} else {
other
statements
}</
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,
<
statements
} else if boolean_expression2 {
otherStatements
}
</syntaxhighlight>
===Match===
Simple usage is,
<
boolean_expression1 {
statements
Line 7,981:
statements
}
}</
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,
<
value1 {
statements
Line 7,994:
}
else {}
}</
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.
Line 8,001:
===if-then-else===
<
result = 'met'
}
else{
result = 'not met'
}</
=={{header|Woma}}==
Line 8,013:
===break-if===
Valid inside of a <@> (loop) block.
<syntaxhighlight lang
===continue-if===
Valid inside of a <@> (loop) block.
<syntaxhighlight lang
===if statement===
Valid inside of a function or a <@> (loop) block.
<
condition<?>print(condition)</
=={{header|Wrapl}}==
Line 8,028:
===simple conditional===
Conditionals in Wrapl are expressions. Either success or failure can be omitted from the expression.
<
condition => success
condition // failure</
===goal directed evaluation===
Wrapl's goal directed evaluation can be used to control conditional execution.
The select-right operator <tt>&</tt> produces the values of the right operand for each value produced by the left operand. Thus if the left operand fails to produce any values, the right operand is never evaluated.
<syntaxhighlight lang
The sequence operator <tt>|</tt> produces the values of the left operand followed by the values of the right operand. Thus if the left operand produces enough values (for example in a context where only one value is required), the right operand is never evaluated.
<syntaxhighlight lang
=={{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.
<
if (b) {
System.print(true)
Line 8,058:
System.print()
}</
{{out}}
Line 8,077:
===ifs/elseifs/elses===
Assembly doesn't work on if/else if/else statements(Unless you're using MASM or alike assemblers:)). Rather, it has conditional jumps which work off flags set by the comparison. Take this general statement from C.
<syntaxhighlight lang="c">
if(i>1)
DoSomething
FailedSoContinueCodeExecution.
</syntaxhighlight>
There are actually a number of ways to implement that in assembly. The most typical way would be something like..
<
cmp i, 1
jg _DoSomething
FailedSoContinueCodeExecution
</syntaxhighlight>
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">
if(i>1)
DoSomething
Line 8,096:
DoSomethingElse
FailedSoContinueCodeExecution
</syntaxhighlight>
In this case, we can use our previous example as a skeleton.
<
cmp i, 1
jg _DoSomething
jle _DoSomethingElse
FailedSoContinueCodeExecution
</syntaxhighlight>
This does another state check on the Zero flag(actually jg/jle also check another flag, but that's not overly important) using jle. JumpifLessthanorEqual. Essentially, jle jumps if ZG is set to 1. So, it's jump condition is the opposite to jg.<br>
<br>
One last commonly used condition.
<syntaxhighlight lang="c">
if(i==1)
DoSomething
Line 8,113:
DoSomethingElse
FailedSoContinueExecution
</syntaxhighlight>
In this case, we'd do this.
<
cmp i, 1
je _DoSomething
jne _DoSomethingElse
FailedSoContinueExecution
</syntaxhighlight>
The je/jne jump instructions are again like jg/jle opposites of each other and again like je/jne rely on how the zero flag is set in the previous comparison. <br>
There are many different conditional jumps in assembly and many ways to set them, test, and, or to name a few. The ones covered are just some commonly used ones in order to show how assembly deals with conditional statements.
Line 8,128:
===If===
An <code>IF</code> expression has the form <code>(IF <condition> <then-clause> <opt-else-clause>)</code>, for example:
<
"The well-known programming chrestomathy site"
"Some other website, maybe, I dunno" )</
If the condition evaluates to anything except <code>NIL</code> or the empty list (which are equivalent), it is counted as true and the whole expression evaluates to the value of the <i>then</i> clause; otherwise it evaluates to the value of the optional <i>else</i> clause, if one is provided, or else to the empty list.
===Case===
<code>CASE</code> expressions resemble the multi-way branching constructs found in most programming languages: an expression is evaluated, and the value of the whole expression is provided by the first clause that evaluates to a true value. Optionally, an <code>ELSE</code> expression can be provided, in case none of the clauses fits.
<
("Rosetta Code" "Ah yes, the chrestomathy site")
("Stack Overflow" "Oh dear me, having problems are you?")
("Github" "Say no more")
(else "Sorry, never heard of it") )</
===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.
<
((eq s "Rosetta Code") "Chrestomathy site")
((> n 37) "Some other appropriate value, presumably")
(t "If you're seeing me, s wasn't equal to Rosetta Code and n must have been 37 or below") )</
=={{header|XPL0}}==
Line 8,167:
=={{header|XSLT}}==
The <xsl:if> element allows simple conditional processing.
<
<!-- executed if XPath expression evaluates to true -->
</xsl:if></
The <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements allow more general conditional processing.
<
<xsl:when test="condition1">
<!-- included if condition1 evaluates to true (like C `if`) -->
Line 8,187:
<!-- (The `otherwise` element is optional) -->
</xsl:otherwise>
</xsl:choose></
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).
<
<xsl:if test="position() != last()">...</xsl:if>
<xsl:if test="not(false())">...</xsl:if>
Line 8,201:
implicitly converted to boolean. -->
<xsl:if test="boolean($expr)">...</xsl:if>
<xsl:if test="$expr">...</xsl:if></
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
// if-then-endif, switch / end switch
// on gosub, on goto
Line 8,271:
sentencia(s)
end while
</syntaxhighlight>
Line 8,282:
We'll look at this example in C and in Z80 Assembly:
<syntaxhighlight lang="c">
char x;
if (x == 20)
Line 8,291:
{
doThat();
}</
<
jr nz,Else
call doThis
Line 8,300:
Else:
call doThat
done</
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:
C code:
<
{
DoSomething();
}
// rest of program</
Z80 Assembly code:
<
cp 20
call z,DoSomething
;rest of program</
If the accumulator didn't equal 20, no <code>CALL</code> will actually take place.
Line 8,323:
===Switch===
Switch cases can be implemented in a few ways. The simplest way is by checking each value individually.
<
cp 1 ;case (1)
jr nz,+ ;branch to next colon (note: not all assemblers support this syntax)
Line 8,336:
call HL_EQUALS_50
:
;rest of program</
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:
<
cp 1 ;case (1)
jr nz,+ ;branch to next lone colon
Line 8,355:
:
done:
;rest of program</
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.
<
add a ;this is a table of 16-bit values, so multiply the index by 2.
ld a,(hl) ;get the low byte of the function addr. you wish to call
Line 8,368:
pop af
ld L,a ;store the low byte in L
jp (HL) ;now you've jumped to the desired function. Its RET will return execution to the instruction just after "CALL Dispatch"</
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}}==
<
if(a)b else if (c) else d; etc
x:=(if (a) b else c);
Line 8,385:
case(b){...}
else {...} // case a C's default, has to be at the end
}</
=={{header|Zig}}==
<
const builtin = @import("builtin");
Line 8,450:
// TODO Arithmetic if once https://github.com/ziglang/zig/issues/8220 is finished
}</
{{omit from|GUISS}}
|