Conditional structures

From Rosetta Code
Jump to: navigation, search
Task
Conditional structures
You are encouraged to solve this task according to the task description, using any language you may know.
Control Structures

These are examples of control structures. You may also be interested in:

This page lists the conditional structures offered by different programming languages. Common conditional structures are if-then-else and switch.

Contents

[edit] 360 Assembly

Here are the branch mnemonic opcodes:

* Unconditional Branch or No Branch:
B label Unconditional
BR Rx "
NOP label No Operation
NOPR Rx "
* After Compare Instructions
BH label Branch on High
BHR Rx "
BL label Branch on Low
BLR Rx "
BE label Branch on Equal
BER Rx "
BNH label Branch on Not High
BNHR Rx "
BNL label Branch on Not Low
BNLR Rx "
BNE label Branch on Not Equal
BNER Rx "
* After Arithmetic Instructions:
BP label Branch on Plus
BPR Rx "
BM label Branch on Minus
BMR Rx "
BZ label Branch on Zero
BZR Rx "
BO label Branch on Overflow
BOR Rx "
BNP label Branch on Not Plus
BNPR Rx "
BNM label Branch on Not Minus
BNMR Rx "
BNZ label Branch on Not Zero
BNZR Rx "
BNO label Branch on No Overflow
BNOR Rx "
* After Test Under Mask Instructions:
BO label Branch if Ones
BOR Rx "
BM label Branch if Mixed
BMR Rx "
BZ label Branch if Zero
BZR Rx "
BNO label Branch if Not Ones
BNOR Rx "
BNM label Branch if Not Mixed
BNMR Rx "
BNZ label Branch if Not Zero
BNZR Rx "

[edit] 6502 Assembly

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:

		LDA #10
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.

		BNE 		;Branch on Not Equal - branch when the zero flag is set
BEQ ;Branch on EQual - branch when the zero flag is set.
;The zero flag is set when the result of an operation is zero
 
BMI ;Branch on MInus
BPL ;Branch on PLus - branch when the sign flag is cleared/set.
;The sign flag is set when the result of an instruction is a negative number
;and cleared when the result is a positive number
 
BVS ;Branch on oVerflow Set
BVC ;Branch on oVerflow Cleared - branch when the overflow flag is cleared/set.
;The overflow flag is set when the result of an addition/subtraction would
;result in a number larger than 127 or smaller than -128
 
BCS ;Branch on Carry Set
BCC ;Branch on Carry Clear - branch when the carry flag is cleared/set.
;The carry flag is set when an addition produced a carry and when
;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:

		LDA #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 interative loops:

		LDX #100
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.

[edit] ActionScript

See JavaScript

[edit] Ada

[edit] if-then-else

type Restricted is range 1..10;
My_Var : Restricted;
 
if My_Var = 5 then
-- do something
elsif My_Var > 5 then
-- do something
else
-- do something
end if;

[edit] case with a default alternative

type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
Today : Days;
 
case Today is
when Saturday | Sunday =>
null;
when Monday =>
Compute_Starting_Balance;
when Friday =>
Compute_Ending_Balance;
when others =>
Accumulate_Sales;
end case;

[edit] case without a default

When there is no when others clause, the compiler will complain about any uncovered alternative. This defends against a common reason for bugs in other languages. I.e., the following code is syntactically incorrect:

case Today is
when Monday =>
Compute_Starting_Balance;
when Friday =>
Compute_Ending_Balance;
when Tuesday .. Thursday =>
Accumulate_Sales;
-- ignore Saturday and Sunday
end case;

The syntactically correct version:

case Today is
when Saturday | Sunday =>
null; -- don't do anything, if Today is Saturday or Sunday
when Monday =>
Compute_Starting_Balance;
when Friday =>
Compute_Ending_Balance;
when Tuesday .. Thursday =>
Accumulate_Sales;
end case;

[edit] select

Select provides conditional acceptance of entry calls. Select can also be used to conditionally call an entry

[edit] Conditional Accept

select
accept first_entry;
-- do something
or accept second_entry;
-- do something
or terminate;
end select;

[edit] 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.

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

[edit] Aikido

[edit] Conditional Expressions

 
var x = loggedin ? sessionid : -1
 
 

[edit] if..elif..else

 
if (value > 40) {
println ("OK")
} elif (value < 20) {
println ("FAILED")
} else {
println ("RETRY")
}
 

[edit] switch

 
switch (arg) {
case "-d":
case "--debug":
debug = true
break
case "-f":
force = true
break
default:
throw "Unknown option " + arg
}
 
switch (value) {
case > 40:
println ("OK")
break
case < 20:
println ("FAILED")
break
case in 50..59:
println ("WIERD")
// fall through
default:
println ("RETRY")
}
 

[edit] Aime

[edit] If-elif-else

if (c1) {
// first condition is true...
} elif (c2) {
// second condition is true...
} elif (c3) {
// third condition is true...
} else {
// none was true...
}

[edit] ALGOL 68

See Conditional Structures/ALGOL 68

[edit] AmbientTalk

[edit] If-then-else

In AmbientTalk, if:then:else: is a keyworded message (as in Smalltalk). The first argument should be a boolean expression. The second and third arguments should be blocks (aka anonymous functions or thunks).

 
if: condition then: {
// condition is true...
} else: {
// condition is false...
}
 

[edit] IfTrue/IfFalse

One can also send a message to the boolean objects true and false:

 
condition.ifTrue: { /* condition is true... */ } ifFalse: { /* condition is false... */ }
 

[edit] AmigaE

IF-THEN-ELSE

IF condition
-> if condition is true...
ELSEIF condition2
-> else if condition2 is true...
ELSE
-> if all other conditions are not true...
ENDIF

or on one single line:

IF condition THEN statement

Ternary IF THEN ELSE

The IF-THEN-ELSE can be used like ternary operator (?: in C)

DEF c
c := IF condition THEN 78 ELSE 19

SELECT-CASE

SELECT var
CASE n1
-> code
CASE n2
-> code
DEFAULT
-> no one of the previous case...
ENDSELECT

Another version allows for ranges:

SELECT max_possible_value OF var
CASE n1
-> code
CASE n2 TO n3, n4
-> more
CASE n5 TO n6, n7 TO n8
-> more...
DEFAULT
-> none of previous ones
ENDSELECT

The biggest among n1, n2 and so on, must be not bigger than max_possible_value.

[edit] AppleScript

[edit] if-then-else

if myVar is "ok" then return true
 
set i to 0
if i is 0 then
return "zero"
else if i mod 2 is 0 then
return "even"
else
return "odd"
end if

[edit] AutoHotkey

[edit] if, else if, else

x = 1
If x
MsgBox, x is %x%
Else If x > 1
MsgBox, x is %x%
Else
MsgBox, x is %x%

[edit] ternary if

x = 2
y = 1
var := x > y ? 2 : 3
MsgBox, % var
 
===while (looping if)===
<lang AutoHotkey>While (A_Index < 3) {
MsgBox, %A_Index% is less than 3
}

[edit] AutoIt

[edit] If, ElseIf, Else

If <expression> Then
statements
...
[ElseIf expression-n Then
[elseif statements ... ]]
...
[Else
[else statements]
...
EndIf
 

[edit] Select Case

Select
Case <expression>
statement1
...
[Case
statement2
...]
[Case Else
statementN
...]
EndSelect
 

[edit] Switch Case

Switch <expression>
Case <value> [To <value>] [,<value> [To <value>] ...]
statement1
...
[Case <value> [To <value>] [,<value> [To <value>] ...]
statement2
...]
[Case Else
statementN
...]
EndSwitch
 

--BugFix (talk) 15:39, 13 November 2013 (UTC)

[edit] AWK

Conditionals in awk are modelled after C:

if(i<0) i=0; else i=42

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:

i=(i<0? 0: 42)

[edit] Babel

[edit] Simple select

 
"foo" "bar" 3 4 > sel <<
 

Prints "foo" since '3 4 >' evaluates to false, which causes sel to remove "bar" from the stack.

[edit] If-Then-Else

 
{3 4 >}
{"foo"}
{"bar"}
ifte
<<
 

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.

[edit] Conditional

 
({3 4 >} {"Three is greater than four" }
{3 3 >} {"Three is greater than three"}
{3 2 >} {"Three is greater than two" }
{3 1 >} {"Three is greater than one" })
cond
<<
 

Prints "Three is greater than two", as expected.

[edit] BASIC

[edit] if-then-else

BASIC can use the if statement to perform conditional operations:

10 LET A%=1: REM A HAS A VALUE OF TRUE
20 IF A% THEN PRINT "A IS TRUE"
30 WE CAN OF COURSE USE EXPRESSIONS
40 IF A%<>0 THEN PRINT "A IS TRUE"
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:

Works with: QuickBasic version 4.5
Works with: FreeBASIC version 0.20.0

Single line IF does not require END IF

IF x = 0 THEN doSomething
IF x < 0 THEN doSomething ELSE doOtherThing

Multi-line IF:

IF x > 0 AND x < 10 THEN
'do stuff
ELSE IF x = 0 THEN
'do other stuff
ELSE
'do more stuff
END IF

Like in C, any non-zero value is interpreted as True:

IF aNumber THEN
'the number is not 0
ELSE
'the number is 0
END IF

[edit] select case

Works with: QuickBasic version 4.5
Works with: FreeBASIC version 0.20.0

The condition in each case branch can be one or more constants or variables, a range or an expression.

SELECT CASE expression
CASE 1
'do stuff
CASE 2, 3
'do other stuff
CASE 3.1 TO 9.9
'do this
CASE IS >= 10
'do that
CASE ELSE
'default case
END SELECT

[edit] Computed ON-GOTO

Older line-numbered BASICs had a mechanism for vectoring execution based on the contents of a numeric variable (a low-budget case statement).

ON V GOTO 120,150,150,170

or:

10 INPUT "Enter 1,2 or 3: ";v
20 GOTO v * 100
99 STOP
100 PRINT "Apple"
110 STOP
200 PRINT "Banana"
210 STOP
300 PRINT "Cherry"
310 STOP

[edit] Conditional loops

Some variants of basic support conditional loops:

10 REM while loop
20 L=0
30 WHILE L<5
40 PRINT L
50 L=L+1
60 WEND
70 REM repeat loop
80 L=1
90 REPEAT
100 PRINT L
110 L=L+1
120 UNTIL L>5

[edit] BBC BASIC

      REM Single-line IF ... THEN ... ELSE (ELSE clause is optional):
IF condition% THEN statements ELSE statements
 
REM Multi-line IF ... ENDIF (ELSE clause is optional):
IF condition% THEN
statements
ELSE
statements
ENDIF
 
REM CASE ... ENDCASE (OTHERWISE clause is optional):
CASE expression OF
WHEN value1: statements
WHEN value2: statements
...
OTHERWISE: statements
ENDCASE
 
REM ON ... GOTO (ELSE clause is optional):
ON expression% GOTO dest1, dest2 ... ELSE statements
 
REM ON ...GOSUB (ELSE clause is optional):
ON expression% GOSUB dest1, dest2 ... ELSE statements
 
REM ON ... PROC (ELSE clause is optional):
ON expression% PROCone, PROCtwo ... ELSE statements

[edit] Befunge

Befunge only has one conditional structure, which comes in two flavors: vertical IF ( | ) and horizontal IF ( _ ). Befunge only has two boolean commands, greater-than ( ` ) and not ( ! ). These snippets input a number and use the conditional operators to print a "0" if it is zero and an "X" otherwise.

v   > "X",@ non-zero
> & |
> "0",@ zero

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

& #v_ "0",@ zero
> "X",@ non-zero

[edit] Bori

[edit] if-elif-else

 
if (i == 0)
return "zero";
elif (i % 2)
return "odd";
else
return "even";
 

[edit] Bracmat

[edit] "if .. then .. else .." type of branching

Bracmat uses & and | for branching. These binary operators are like && and || in C-like languages. Bracmat does not have the notion of Boolean variables, but marks all evaluated expressions as either succeeded or failed. If the left hand side of the & operator has succeeded, Bracmat goes on evaluating the right hand side. Only if both of left and right hand sides succeed, the expression tree headed by the & operator as a whole succeeds. Likewise, only if both of left and right hand sides of an expression tree headed by | fail, the expression tree as a whole fails. Evaluated expressions are just that: expressions. The following expression writes "That's what I thought." to your screen and evaluates to the expression "Right".

    2+2:5
& put$"Strange, must check that Bracmat interpreter."
& 0
| put$"That's what I thought."
& Right

[edit] switch-like branching

Use a patterns with alternations. Note that the match-expression (the tree headed by the : operator) evaluates to the left hand side of the : operator. In the following example, the resulting expression is a single node containing "4".

  2+2
: ( (<3|>5)
& put$"Not quite, must check that Bracmat interpreter."
| (3|5)
& put$"Not far off, but must check that Bracmat interpreter some day."
|  ?
& put$"That's what I thought."
)
 

[edit] Brainf***

Brainf*** has two conditional jump instructions, [ and ]. the [ instruction jumps forward to the corresponding ] instruction if the value at the current memory cell is zero, while the ] instruction jumps back if the current memory cell is nonzero. Thus in the following sequence:

[.]

The . instruction will be skipped, while the following sequence

+[.]

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

+[.-]

The . instruction will be executed once.

[edit] Burlesque

Using the Choose command:

 
blsq ) 9 2.%{"Odd""Even"}ch
"Odd"
 

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

 
blsq ) 9^^2.%{+.}if
10
blsq ) 10^^2.%{+.}if
10
 

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
 

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"
 

[edit] C

See Conditional Structures/C

[edit] C++

[edit] Run-Time Control Structures

See C

[edit] Compile-Time Control Structures

[edit] Preprocessor Techniques

See C

[edit] Template metaprogramming

Selecting a type depending on a compile time condition

template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;
 
template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
{
typedef ThenType type;
};
 
template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>
{
typedef ElseType type;
};
 
// example usage: select type based on size
ifthenelse<INT_MAX == 32767, // 16 bit int?
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

[edit] Clean

[edit] if

There are no then or else keyword in Clean. The second argument of if is the then-part, the third argument is the else-part.

bool2int b = if b 1 0

[edit] case-of

case 6 * 7 of
42 -> "Correct"
_ -> "Wrong" // default, matches anything

[edit] function alternatives

answer 42 = True
answer _ = False

[edit] guards

answer x
| x == 42 = True
| otherwise = False
 
case 6 * 7 of
n | n < 0 -> "Not even close"
42 -> "Correct"
// no default, could result in a run-time error

[edit] Clipper

if-elseif-else-endif

IF x == 1
SomeFunc1()
ELSEIF x == 2
SomeFunc2()
ELSE
SomeFunc()
ENDIF

do case

DO CASE
CASE x == 1
SomeFunc1()
CASE x == 2
SomeFunc2()
OTHERWISE
SomeFunc()
ENDCASE

[edit] Clojure

[edit] if-then-else

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

[edit] when

Similar to if, but body in an implicit do block allowing multiple statements. No facility for providing an else. when is defined as a macro.

(when x
(print "hello")
(println " world")
5) ; when x is logical true, prints "hello world" and returns 5; otherwise does nothing, returns nil

[edit] 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.

(cond
(= 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.

(cond
(= 1 2) :no
 :else :yes) ; returns :yes

[edit] condp

Similar to cond, but useful when each test differs by only one variant.

(condp < 3
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.

(condp < 3
4 :a
3 :b
 :no-match) ; returns :no-match

[edit] case

Works with: Clojure version 1.2
(case 2
0 (println "0")
1 (println "1")
2 (println "2")) ; prints 2.

[edit] CMake

set(num 5)
 
if(num GREATER 100)
message("${num} is very large!")
elseif(num GREATER 10)
message("${num} is large.")
else()
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 cmake --help-command if. The elseif() and else() sections are optional.

[edit] COBOL

[edit] if-then-else

if condition-1
imperative-statement-1
else
imperative-statement-2
end-if
 
if condition-1
if condition-a
imperative-statement-1a
else
imperative-statement-1
end-if
else
if condition-a
imperative-statement-2a
else
imperative-statement-2
end-if
end-if

[edit] evaluate

evaluate identifier-1
when 'good'
good-imperative-statement
when 'bad'
bad-imperative-statement
when 'ugly'
when 'awful'
ugly-or-awful-imperative-statement
when other
default-imperative-statement
end-evaluate
 
evaluate true
when condition-1
condition-1-imperative-statement
when condition-2
condition-2-imperative-statement
when condition-3
condition-3-imperative-statement
when other
default-condition-imperative-statement
end-evaluate
 
evaluate identifier-1 also identifier-2
when 10 also 20
one-is-10-and-two-is-20-imperative-statement
when 11 also 30
one-is-11-and-two-is-30-imperative-statement
when 20 also any
one-is-20-and-two-is-anything-imperative-statement
when other
default-imperative-statement
end-evaluate

[edit] CoffeeScript

[edit] if-then-else

 
if n == 1
console.log "one"
else if n == 2
console.log "two"
else
console.log "other"
 

[edit] switch

n = 1
 
switch n
when 1
console.log "one"
when 2, 3
console.log "two or three"
else
console.log "other"
 

[edit] ternary expressions

CoffeeScript is very expression-oriented, so you can assign the "result" of an if-then to a variable.

s = if condition then "yup" else "nope"
 
# alternate form
s = \
if condition
then "yup"
else "nope"

[edit] ColdFusion

[edit] if-elseif-else

Compiler: ColdFusion any version

<cfif x eq 3>
do something
<cfelseif x eq 4>
do something else
<cfelse>
do something else
</cfif>

[edit] switch

Compiler: ColdFusion any version

<cfswitch expression="#x#">
<cfcase value="1">
do something
</cfcase>
<cfcase value="2">
do something
</cfcase>
<cfdefaultcase>
do something
</cfdefaultcase>
</cfswitch>

[edit] Common Lisp

There are 2 main conditional operators in common lisp, (if ...) and (cond ...).

[edit] (if cond then [else])

The (if ...) construct takes a predicate as its first argument and evaluates it. 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.

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

[edit] when and unless

Common Lisp also includes (when condition form*) and (unless condition form*) which are equivalent, respectively, to (if condition (progn form*)) and (if (not condition) (progn form*)).

It is unidiomatic to use if without an else branch for side effects; when should be used instead.

[edit] (cond (pred1 form1) [... (predN formN)])

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.

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

[edit] Crack

[edit] if-elseif-else

if (condition)
{
// Some Task
}
 
if (condition)
{
// Some Task
}
else if (condition2)
{
// Some Task
}
else
{
// Some Task
}

[edit] Ternary

 
// if condition is true var will be set to 1, else false.
int var = condition ? 1 : 2;
 


[edit] C#

[edit] if-elseif-else

if (condition)
{
// Some Task
}
 
if (condition)
{
// Some Task
}
else if (condition2)
{
// Some Task
}
else
{
// Some Task
}

[edit] Ternary

// if condition is true var will be set to 1, else 2.
int var = condition ? 1 : 2;

[edit] switch

switch (value)
{
case 1:
// Some task
break; // Breaks are required in C#.
case 2:
case 3:
// Some task
break;
default: // If no other case is matched.
// Some task
break;
}

If fall through algorithms are required use the goto keyword.

switch (value)
{
case 1:
// Some task
goto case 2; // will cause the code indicated in case 2 to be executed.
case 2:
// Some task
break;
case 3:
// Some task
break;
default: // If no other case is matched.
// Some task
break;
}

[edit] Batch File

IF syntax:

 
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
IF CMDEXTVERSION number command
IF DEFINED variable command
IF [/I] string1 compare-op string2 command
where compare-op is:
EQU - equal
NEQ - not equal
LSS - less than
LEQ - less than or equal
GTR - greater than
GEQ - greater than or equal
/I case insensitive string compares
 

The ELSE clause must be on the same line as the command after the IF. For example:

 
IF EXIST %filename% (
del %filename%
) ELSE (
echo %filename% not found
)
 


[edit] D

See C, sans the preprocessor.
void main() {
enum int i = 5;
 
// "static if" for various static checks:
static if (i == 7) {
// ...
} else {
//...
}
 
// is(T == U) checks if type T is U.
static if (is(typeof(i) == int)) {
// ...
} else {
// ...
}
 
// D switch is improved over C switch:
switch (i) {
case 0:
break; // Silent fallthrough is forbidden.
case 1:
goto case; // Explicit fallthrough.
case 2:
// Empty cases don't require an explicit fallthrough.
case 3:
return;
case 4, 5, 7: // Multiple cases.
break;
case 8: .. case 15: // Inclusive interval.
goto case 3;
default: // Default case is required.
break;
}
 
enum Colors { yellow, blue, brown, green }
immutable c = Colors.blue;
 
// "final switch" is safer, for enums (and in future other values,
// like Algebraic), because all cases must be present.
// with() is handy to avoid repeating "Colors." for each case.
final switch (c) with (Colors) {
case yellow: break;
case blue: break;
case brown, green: break;
// case yellow: .. case brown: // Forbidden in final switches.
// default: // Forbidden in final switches.
}
}

[edit] Dao

[edit] If Elif Else

a = 3
if( a == 1 ){
io.writeln( 'a == 1' )
}else if( a== 3 ){
io.writeln( 'a == 3' )
}else{
io.writeln( 'a is neither 1 nor 3' )
}

[edit] Switch Case

a = 3
switch( a ){
case 0: io.writeln( 'case 0' )
case 1, 2: io.writeln( 'case 1,2' )
case 3, 4, 5: io.writeln( 'case 3,4,5' )
default: io.writeln( 'default' )
}

[edit] Déjà Vu

if a:
pass
elseif b:
pass
else: # c, maybe?
pass

[edit] Deluge

if (input.Field == "Hello World") {
sVar = "good";
} else if (input.Field == "Bye World") {
sVar = "bad";
} else {
sVar = "neutral";
}

[edit] Delphi

See Pascal

[edit] DWScript

See Pascal

[edit] E

[edit] if-then-else

if (okay) {
println("okay")
} else if (!okay) {
println("not okay")
} else {
println("not my day")
}

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

println(okay.pick("okay", "not okay"))

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

okay.pick(fn {
println("okay")
}, fn {
println("not okay")
})()

All of the above conditionals are expressions and have a usable return value.

[edit] switch

E's "switch" allows pattern matching.

def expression := ["+", [1, 2]]
 
def value := switch (expression) {
match [`+`, [a, b]] { a + b }
match [`*`, [a, b]] { a * b }
match [op, _] { throw(`unknown operator: $op`) }
}

[edit] Efene

The expressions can contain parenthesis or not, here both options are shown. 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) {
io.format("is one~n")
}
else if (Num === 2) {
io.format("is two~n")
}
else {
io.format("not one not two~n")
}
}
 
show_if_without_parenthesis = fn (Num) {
if Num == 1 {
io.format("is one~n")
}
else if Num === 2 {
io.format("is two~n")
}
else {
io.format("not one not two~n")
}
}
 
show_switch_with_parenthesis = fn (Num) {
switch (Num) {
case (1) {
io.format("one!~n")
}
case (2) {
io.format("two!~n")
}
else {
io.format("else~n")
}
}
}
 
show_switch_without_parenthesis = fn (Num) {
switch (Num) {
case 1 {
io.format("one!~n")
}
case 2 {
io.format("two!~n")
}
else {
io.format("else~n")
}
}
}
 
@public
run = fn () {
show_if_with_parenthesis(random.uniform(3))
show_if_without_parenthesis(random.uniform(3))
 
show_switch_with_parenthesis(random.uniform(3))
show_switch_without_parenthesis(random.uniform(3))
}

[edit] Ela

[edit] if-then-else

if x < 0 then 0 else x

[edit] Guards

getX x | x < 0 = 0
| else = x

[edit] Pattern matching

force (x::xs) = x :: force xs
force [] = []

[edit] match expression

force lst = match lst with
x::xs = x :: force xs
[] = []

[edit] Erlang

Erlang's conditionals are based on pattern matching and guards. There are several mechanisms for this: case-of, if, function clauses. Pattern matching allows destructuring a term and matches a clause based on the structure. In the case example the term is X and the pattern is {N,M} or _. _ will match anything, while {N,M} will only match tuples of two terms. Though N and M could be any other type (in this case an error will occur if they're non-numeric). Guards allow more specification on the terms from the matched pattern. In the case example comparing N and M are guards.

[edit] case

case expressions take an expression and match it to a pattern with optional guards.

case X of
{N,M} when N > M -> M;
{N,M} when N < M -> N;
_ -> equal
end.

[edit] if

if expressions match against guards only, without pattern matching. Guards must evaluate to true or false so true is the catch-all clause.

{N,M} = X,
if
N > M -> M;
N < M -> N;
true -> equal
end.

[edit] Function Clauses

Functions can have multiple clauses tested in order.

test({N,M}) when N > M -> M;
test({N,M}) when N < M -> N;
test(_) -> equal.

[edit] Factor

There are many conditional structures in Factor. Here I'll demonstrate the most common ones. A few of these have other variations that abstract common stack shuffle patterns. I will not be demonstrating them.

[edit] ?

? is for when you don't need branching, but only need to select between two different values.

 
t 1 2 ? ! returns 1
 

[edit] if

t [ 1 ] [ 2 ] if ! returns 1

[edit] cond

{ { [ t ] [ 1 ] } { [ f ] [ 2 ] } } cond ! returns 1

[edit] case

t { { t [ 1 ] } { f [ 2 ] } } case ! returns 1

[edit] when

t [ "1" print ] when ! prints 1

[edit] unless

f [ "1" print ] unless ! prints 1

[edit] FALSE

condition[body]?

Because there is no "else", you need to stash the condition if you want the same effect:

$[\true\]?~[false]?

or

$[%true0~]?~[false]?

[edit] Fancy

Fancy has no built-in conditional structures. It uses a combination of polymorphism and blockliterals (closures) to achieve the same thing (like Smalltalk).

[edit] if:then:

if: (x < y) then: {
"x < y!" println # will only execute this block if x < y
}
 

[edit] if:then:else::

if: (x < y) then: {
"x < y!" println # will only execute this block if x < y
} else: {
"x not < y!" println
}
 


[edit] if_true:

x < y if_true: {
"x < y!" println # will only execute this block if x < y
}
 

[edit] if_false: / if_nil:

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

[edit] if_true:else:

x < y if_true: {
"x < y!" println
} else: {
"x >= y!" println
}
 

[edit] if_false:else:

x < y if_false: {
"x >= y!"
} else: {
"x < y!" println
}
 

[edit] if:

{ "x < y!" println } if: (x < y)   # analog, but postfix


[edit] unless:

{ "x not < y!" } unless: (x < y)   # same here

[edit] Forth

[edit] IF-ELSE

( condition ) IF ( true statements ) THEN
( condition ) IF ( true statements ) ELSE ( false statements ) THEN

example:

10 < IF ." Less than 10" ELSE ." Greater than or equal to 10" THEN

[edit] CASE-OF

( n -- ) CASE
( integer ) OF ( statements ) ENDOF
( integer ) OF ( statements ) ENDOF
( default instructions )
ENDCASE

example: a simple CASE selection

: test-case ( n -- )
CASE
0 OF ." Zero!" ENDOF
1 OF ." One!" ENDOF
." Some other number!"
ENDCASE ;

[edit] Execution vector

To obtain the efficiency of a C switch statement for enumerations, one needs to construct one's own execution vector.

: switch
CREATE ( default-xt [count-xts] count -- ) DUP , 0 DO , LOOP ,
DOES> ( u -- ) TUCK @ MIN 1+ CELLS + @ EXECUTE ;
 
 :NONAME ." Out of range!" ;
 :NONAME ." nine" ;
 :NONAME ." eight" ;
 :NONAME ." seven" ;
 :NONAME ." six" ;
 :NONAME ." five" ;
 :NONAME ." four" ;
 :NONAME ." three" ;
 :NONAME ." two" ;
 :NONAME ." one" ;
 :NONAME ." zero" ;
10 switch digit
 
8 digit \ eight
34 digit \ Out of range!

[edit] Fortran

In ISO Fortran 90 and later, there are three conditional structures. There are also a number of other *unstructured* conditional statements, all of which are old and many of which are marked as "deprecated" in modern Fortran standards. These examples will, as requested, only cover conditional *structures*:

[edit] IF-THEN-ELSE

ANSI FORTRAN 77 or later has an IF-THEN-ELSE structure:

if ( a .gt. 20.0 ) then
q = q + a**2
else if ( a .ge. 0.0 ) then
q = q + 2*a**3
else
q = q - a
end if

[edit] SELECT-CASE

ISO Fortran 90 or later has a SELECT-CASE structure:

select case (i)
case (21:) ! matches all integers greater than 20
q = q + i**2
case (0:20) ! matches all integers between 0 and 20 (inclusive)
q = q + 2*i**3
case default ! matches all other integers (negative in this particular case)
q = q - I
end select

[edit] 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.

! diffusion grid time step
where (edge_type(1:n,1:m) == center)
anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5
 
elsewhere (edge_type(1:n,1:m) == left)
anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5
 
elsewhere (edge_type(1:n,1:m) == right)
anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + a(1:n,0:m-1) + a(1:n,2:m+1)) / 5
 
elsewhere (edge_type(1:n,1:m) == top)
anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + 2*a(1:n,2:m+1)) / 5
 
elsewhere (edge_type(1:n,1:m) == bottom)
anew(1:n,1:m) = (a(1:n,1:m) + a(0:n-1,1:m) + a(2:n+1,1:m) + 2*a(1:n,0:m-1)) / 5
 
elsewhere (edge_type(1:n,1:m) == left_top)
anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + 2*a(1:n,2:m+1)) / 5
 
elsewhere (edge_type(1:n,1:m) == right_top)
anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + 2*a(1:n,2:m+1)) / 5
 
elsewhere (edge_type(1:n,1:m) == left_bottom)
anew(1:n,1:m) = (a(1:n,1:m) + 2*a(2:n+1,1:m) + 2*a(1:n,0:m-1)) / 5
 
elsewhere (edge_type(1:n,1:m) == right_bottom)
anew(1:n,1:m) = (a(1:n,1:m) + 2*a(0:n-1,1:m) + 2*a(1:n,0:m-1)) / 5
 
elsewhere ! sink/source, does not change
anew(1:n,1:m) = a(1:n,1:m)
end where

[edit] friendly interactive shell

[edit] if-then-else

set var 'Hello World'
if test $var = 'Hello World'
echo 'Welcome.'
else if test $var = 'Bye World'
echo 'Bye.'
else
echo 'Huh?'
end

[edit] 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.

switch actually
case az
echo The word is "az".
case 'a*z'
echo Begins with a and ends with z.
case 'a*'
echo Begins with a.
case 'z*'
echo Ends with z.
case '*'
echo Neither begins with a or ends with z.
end

[edit] GAP

[edit] if-then-else

if <condition> then
<statements>
elif <condition> then
<statements>
else
<statements>
fi;

[edit] Go

If and switch are the general purpose conditional structures in Go, although the language certainly contains other conditional elements.

[edit] If

Simplest usage is,

if booleanExpression {
statements
}

The braces are required, even around a single statement.

if booleanExpression {
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,

if booleanExpression1 {
statements
} else if booleanExpression2 {
otherStatements
}
 

If allows a statement to be included ahead of the condition. This is commonly a short variable declaration, as in,

if x := fetchSomething(); if x > 0 {
DoPos(x)
} else {
DoNeg(x)
}

In this case the scope of x is limited to if statement.

[edit] Switch

Simple usage is,

switch {
case booleanExpression1:
statements
case booleanExpression2:
other
statements
default:
last
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,

switch expressionOfAnyType {
case value1:
statements
case value2, value3, value4:
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:

switch x := fetch(); {
case x == "cheese":
statements
case otherBooleanExpression:
other
statements
}

Also, as with if, the scope of x is limited to the switch statement.

Execution does not normally fall through from one case clause to the next, but this behavior can be forced with a fallthrough statement.

An interesting example:

switch {
case booleanExpression1:
default:
statements
preliminaryToOtherStatements
fallthrough
case booleanExpression2:
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.

for {
switch {
case true:
break
}
fmt.Println("I want out!")
}

Labels provide the desired capability. The following prints "I'm off!"

treadmill: for {
switch {
case true:
break treadmill
}
}
fmt.Println("I'm off!")

[edit] Harbour

if-elseif-else-endif

IF x == 1
SomeFunc1()
ELSEIF x == 2
SomeFunc2()
ELSE
SomeFunc()
ENDIF

do case

DO CASE
CASE x == 1
SomeFunc1()
CASE x == 2
SomeFunc2()
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.

SWITCH x
CASE 1
SomeFunc1()
EXIT
CASE 2
SomeFunc2()
EXIT
OTHERWISE
SomeFunc()
ENDSWITCH

[edit] Haskell

[edit] if-then-else

fac x = if x==0 then
1
else x * fac (x - 1)

[edit] Guards

fac x | x==0 = 1
| x>0 = x * fac (x-1)

[edit] Pattern matching

fac 0 = 1
fac x = x * fac (x-1)

[edit] case statement

fac x = case x of 0 -> 1
_ -> x * fac (x-1)

[edit] HicEst

IF( a > 5 ) WRITE(Messagebox) a ! single line IF
 
IF( a >= b ) THEN
WRITE(Text=some_string) a, b
ELSEIF(some_string > "?") THEN
WRITE(ClipBoard) some_string
ELSEIF( nonzero ) THEN
WRITE(WINdowhandle=nnn) some_string
ELSE
WRITE(StatusBar) a, b, some_string
ENDIF

[edit] IDL

[edit] if-else

Basic if/then:

if a eq 5 then print, "a equals five" [else print, "a is something else"]

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:

if a eq 5 then begin
... some code here ...
endif [else begin
... some other code here ...
endelse]

[edit] case

case <expression> of
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[else: <command-else>]
endcase

(Or replace any of the commands with {begin..end} pairs)

[edit] switch

switch <expression> of
(choice-1): <command-1>
[(choice-2): <command-2> [...]]
[else: <command-else>]
endswitch

The switch will execute all commands starting with the matching result, while the case will only execute the matching one.

[edit] on_error

on_error label

Will resume execution at label when an error is encountered. on_ioerror is similar but for IO errors.

[edit] Icon and Unicon

All Icon and Unicon expressions, including control structures, yield results or signal failure.

[edit] if-then-else

The control structure evaluates expr1 if expr0 succeeds and expr2 if it fails.

if expr0 then
expr1
else
expr2

[edit] case-of

The first successful selection expression will select and evaluate the specific case.

case expr0 of {
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:

case x of {
f(x) | g(x) : expr2
s(x) & t(x) : expr4
default: expr5
}

[edit] Compound expressions (blocks)

In the examples below, multiple expressions can be grouped as in:

{
expr1
expr2
expr3
}

Which is equivalent to this:

{expr1; expr2; expr3}

For example the following, which will write 4, looks strange but is valid:

write({1;2;3;4})

The value of a compound expression is the value of the last expression in the block.

[edit] Alternation

Alternation of expressions yields a value for the first succeeding expression.

   expr1 | expr2 | expr3

[edit] Conjunction

Conjunctions yeild the value of the final expression provided all the previous expressions succeed.

   expr1 & expr2 & expr3

Alternately, conjunction can be written thus:

   (expr1, expr2, expr3)

[edit] Conjunction, yielding a different result

The alternate form of conjunction can be modified to produce a different result (other than the last)

   expr0(expr1, expr2, expr3)

For example:

   2(expr1, expr2, expr3)

Yields the value of expr2 if all of the expressions succeed.
A more complicated example showing non-constant expressions:

   f(expr1)(g(expr2)(expr3,expr4,expr5))

Note: if expr0 yields a value of type 'procedure' or 'string' the appropriate procedure (or operator) is invoked.

[edit] Inform 7

[edit] if-then-else

[short form]
if N is 1, say "one.";
otherwise say "not one.";
 
[block form]
if N is 1:
say "one.";
otherwise if N is 2:
say "two.";
otherwise:
say "not one or two.";
 
[short and long forms can be negated with "unless"]
unless N is 1, say "not one."

[edit] switch

if N is:
-- 1: say "one.";
-- 2: say "two.";
-- otherwise: say "not one or two.";

[edit] if-then-else in text

say "[if N is 1]one[otherwise if N is 2]two[otherwise]three[end if].";
say "[unless N is odd]even.[end if]";

[edit] other branching text substitutions

Text that may be printed multiple times can also use sequential and random branching:

[a different color every time]
say "[one of]red[or]blue[or]green[at random].";
 
["one" the first time it's printed, "two" the second time, then "three or more" subsequently]
say "[one of]one[or]two[or]three or more[stopping]";
 
[only appears once]
say "[first time]Hello world![only]";

[edit] rulebook approach

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

Number Factory is a room.
 
Number handling is a number based rulebook with default success.
 
Number handling for 1: say "one."
Number handling for 2: say "two."
Number handling for an even number (called N): say "[N in words] (which is even)."
Last number handling rule: say "other."
 
When play begins:
follow the number handling rules for 2;
follow the number handling rules for 4;
follow the number handling rules for 5.

[edit] J

See Conditional Structures/J

[edit] Java

[edit] if-then-else

if(s.equals("Hello World"))
{
foo();
}
else if(s.equals("Bye World"))
bar();//{}'s optional for one-liners
else
{
deusEx();
}

Java also supports short-circuit evaluation. So in a conditional like this:

if(obj != null && obj.foo()){
aMethod();
}

obj.foo() will not be executed if obj != null returns false. It is possible to have conditionals without short circuit evaluation using the & and | operators (from Bitwise operations). So in this conditional:

if(obj != null & obj.foo()){
aMethod();
}

You will get a null pointer exception if obj is null.

[edit] ternary

s.equals("Hello World") ? foo() : bar();

[edit] 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 Strings in Java 7 and higher).

switch(c) {
case 'a':
foo();
break;
case 'b':
bar();
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:

if(c == 'a'){
foo();
}else if(c == 'b'){
bar();
foobar();
}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).

[edit] JavaScript

[edit] if-then-else

if( s == "Hello World" ) {
foo();
} else if( s == "Bye World" ) {
bar();
} else {
deusEx();
}

[edit] switch

switch(object) {
case 1:
one();
break;
case 2:
case 3:
case 4:
twoThreeOrFour();
break;
case 5:
five();
break;
default:
everythingElse();
}

[edit] conditional (ternary) operator (?:)

var num = window.obj ? obj.getNumber() : null;

[edit] jq

jq's main conditional construct is:
if cond then f else g end
where cond, f, and g, are filters, and where cond may evaluate to anything at all, it being understood that:
  1. all JSON values are truthy except for false and null;
  2. 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:

 
if cond then f elif cond1 then f1 .... else g end
 
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
 
Notice that if cond produces a nonempty stream, then the entire expression will typically do the same. Since f and g also can produce streams, this lends itself to interesting Cartesian-product possibilities. There is no "case <exp>" construct, but the idiom illustrated by the following example can be used to avoid the need to create a temporary variable to hold the "case" expression:
 
exp
| if . == true then "true"
elif . == false then "false"
elif . == null then "maybe"
elif type == "string" then .
else error("unexpected value: \(.)")
end

Since jq's and and or are short-circuiting, they can also be used for branching.

[edit] LabVIEW

[edit] Case Structure

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
LabVIEW Case.png

[edit] Select

Select is similar to the Ternary operator in text-based languages.
LabVIEW Select.png

[edit] Lisaac

Works with: Lisaac version 0.13.1

[edit] if-then-else

+ n : INTEGER;
 
n := 3;
 
(n = 2).if {
IO.put_string "n is 2\n";
}.elseif {n = 3} then {
IO.put_string "n is 3\n";
}.elseif {n = 4} then {
IO.put_string "n is 4\n";
} else {
IO.put_string "n is none of the above\n";
};
(n = 2).if_true { "n is 2\n".print; };
(n = 2).if_false { "n is not 2\n".print; };

[edit] when

+ n : INTEGER;
 
n := 3;
n
.when 2 then {
"n is 2\n".print;
}
.when 3 then {
"n is 3\n".print;
}
.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.

[edit]

if :x < 0 [make "x 0 - :x]
 
ifelse emptyp :list [print [empty]] [print :list]

UCB Logo and its descendants have also case:

to vowel? :letter
output case :letter [ [[a e i o u] "true] [else "false] ]
end
show vowel? "e
show vowel? "x
Output:
true
false

Logo also provides TEST which is local to a procedure:

to mytest :arg1 :arg2
test :arg1 = :arg2
iftrue [print [Arguments are equal]]
iffalse [print [Arguments are not equal]]
end

[edit] LSE64

The simple conditionals take single words rather than blocks of statements, as in most other languages.

t : " true"  ,t
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 : drop " Neither one nor two" ,t    # default declared first
onetwo : dup 2 = then " Two" ,t
onetwo : dup 1 = then " One" ,t

Short-circuit operators "&&" and "||" are used for complex conditionals.

dup 0 = || ,t    # avoid printing a null string

[edit] Lua

 
--if-then-elseif-then-else
if a then
b()
elseif c then
d()
else
e()
end
 
for var = start, _end, step do --note: end is a reserved word
something()
end
 
for var, var2, etc in iteratorfunction do
something()
end
 
while somethingistrue() do
something()
end
 
repeat
something()
until somethingistrue()
 
cases = {
key1 = dothis,
key2 = dothat,
key3 = dotheother
}
 
cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively

[edit] Make

An if condition using pure make (no gmake extensions)

# make -f do.mk C=mycond if
C=0
 
if:
-@expr $(C) >/dev/null && make -f do.mk true; exit 0
-@expr $(C) >/dev/null || make -f do.mk false; exit 0
 
true:
@echo "was true."
 
false:
@echo "was false."

Using it

make -f do.mk if C=0
> 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)

C=0
 
if: true false
 
true:
@expr $(C) >/dev/null && exit 0 || exit 1
@echo "was true."
 
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.

|make -f do.mk -s -k C=1
was true.
*** Error code 1
|make -f do.mk -s -k C=0
*** Error code 1
was false.

Using gmake

A=
B=
 
ifeq "$(A)" "1"
B=true
else
B=false
endif
 
do:
@echo $(A) .. $(B)

Using it

|gmake -f if.mk A=1
1 .. true
|gmake -f if.mk A=0
0 .. false

[edit] Maple

Maple offers both conditional statements and conditional functions.

[edit] Conditional statements

Example syntax for conditional statements:

if x > 0 then
res := x;
else
res := -x;
end if;

Example syntax for conditional statements with else-if:

if x = 0 then
res := y;
elif y = 0 then
res := x;
else
res := sqrt(x^2+y^2);
end if;

[edit] Conditional functions

The Maple function `if`(cond,a,b) (note the backtick ` delimiters) returns a when cond is true and b otherwise.

res := `if`(n::even, n/2, 3*n+1);

The piecewise command can be used for functional evaluation in which there is more than one branch. The following is equivalent to the if/then construct from the previous section.

res := piecewise(x=0, y, y=0, x, sqrt(x^2+y^2));

[edit] Mathematica

Usual If[condition,True,False]

Make a definition with the condition that x should be positive: f[x_] := ppp[x] /; x > 0

f[5] gives ppp[5]

f[-6] gives f[-6]

[edit] MATLAB

[edit] If statements

Example:

if x == 1
disp 'x==1';
elseif x > 1
disp 'x>1';
else
disp 'x<1';
end

[edit] Switch statements

Example:

switch x
case 1
disp 'Hello';
case 2
disp 'World';
otherwise
disp 'Skynet Active';
end

[edit] Maxima

if test1 then (...) elseif test2 then (...) else (...);

[edit] MAXScript

[edit] if

if x == 1 then
(
print "one"
)
else if x == 2 then
(
print "two"
)
else
(
print "Neither one or two"
)

[edit] case

Form one

case x of
(
1: (print "one")
2: (print "two")
default: (print "Neither one or two")
)

Form two

case of
(
(x == 1): (print "one")
(x == 2): (print "two")
default: (print "Neither one or two")
)

[edit] MBS

INT x;
x:=0;
IF x = 1 THEN
 ! Do something
ELSE
 ! Do something else
ENDIF;

[edit] Metafont

if conditionA:
 % do something
elseif conditionB:
 % do something
% more elseif, if needed...
else:
 % do this
fi;

The particularity of if construct in Metafont is that it can be part of an expression, and the "do something" does not need to fit into the syntactic structure. E.g. we can write something like

b := if a > 5: 3 + else: 2 - fi c;

Alone, the code 3 + does not mean anything; but once the condition is evaluated, the whole expression must become "correct"; e.g. if a > 5, the expression will be b := 3 + c;.

There are no other kind of conditional structures, but the great flexibility of Metafont allows for sure to create "new syntaxes" similar to switches or whatever needed.

[edit] МК-61/52

Conditional jumps are done by four instructions, comparing the register X with zero:

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

[edit] Modula-2

[edit] if-then-else

IF i = 1 THEN
InOut.WriteString('One')
ELSIF i = 2 THEN
InOut.WriteString('Two')
ELSIF i = 3 THEN
InOut.WriteString('Three')
ELSE
InOut.WriteString('Other')
END;

[edit] Case

CASE i OF
1 : InOut.WriteString('One')
| 2 : InOut.WriteString('Two')
| 3 : InOut.WriteString('Three')
ELSE
InOut.WriteString('Other')
END

[edit] Modula-3

[edit] if-then-else

IF Foo = TRUE THEN
Bar();
ELSE
Baz();
END;
IF Foo = "foo" THEN
Bar();
ELSIF Foo = "bar" THEN
Baz();
ELSIF Foo = "foobar" THEN
Quux();
ELSE
Zeepf();
END;

[edit] Case

CASE Foo OF
| 1 => IO.Put("One\n");
| 2 => IO.Put("Two\n");
| 3 => IO.Put("Three\n");
ELSE
IO.Put("Something\n");
END;

[edit] Type-case

TYPECASE is used on reference types to perform different operations, depending on what it is a reference to.

TYPECASE ref OF
| NULL => IO.Put("Null\n");
| CHAR => IO.Put("Char\n");
| INTEGER => IO.Put("Integer\n");
ELSE
IO.Put("Something\n");
END;

[edit] MUMPS

[edit] If / I and ELSE / E

 IF A list-of-MUMPS-commands

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:

 IF T DO SUBROUTINE
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:

 
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:

 
IF T DO
. DO SUBROUTINE
ELSE DO SOMETHING


[edit] $Select / $S

 WRITE $SELECT(1=2:"Unequal",1=3:"More unequal",1:"Who cares?")

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.

[edit] (command postconditional i.e. colon/:

 SET:(1=1) SKY="Blue"
GOTO:ReallyGo LABEL
QUIT:LoopDone
WRITE:NotLastInSet ","

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.

The exceptions are FOR, IF, and ELSE. There are several commands that also allow for post-conditionals in their arguments. The GOTO, and DO commands must have a label but it optionally have a colon followed by a truth value. When the truth value is interpreted as false, the flow of control does NOT move to the label indicated. If it is true, then flow of control does move to the label. Similarly, the XECUTE command may have a colon and postcondition on its argument, which is a expression that is interpreted as a line of MUMPS code. That code is executed when the postcondition is true, and not executed when it is false. Some people consider timeouts to be a form of conditional. For example in the READ command, a number (or numeric expression) after a colon is the number of seconds to wait for a user to make an entry. If the user doesn't make an entry before the timeout, the special variable $TEST is set to 0 (zero), indicating a timeout has occurred. Likewise in the JOB command, a number (or numeric expression) after a colon is the number of seconds to wait for the system to start a new job running in "parallel" to the current job. If the system does not create a new job before the timeout, the special variable $TEST is set to 0 (zero), indicating a timeout has occurred.

[edit] Nemerle

[edit] if-else

if (cond) <then> else <this>; is an expression in Nemerle, requiring both keywords (if and else) to be valid. when and unless are macros for which <this> = null. cond must be an expression that evaluates to a bool (true|false), other types aren't automatically assigned truth or falsehood as in some languages.

if (the_answer == 42) FindQuestion() else Foo();
when (stock.price < buy_order) stock.Buy();
unless (text < "") Write(text);

[edit] match

Much cleaner than stacked if-else's, similar in some ways to switch-case (but more flexible). See here, here, or, for extra detail, the reference.

match(x)
{
|1 => "x is one"
|x when (x < 5) => "x is less than five"
|_ => "x is at least five"
}

[edit] NetRexx

[edit] IF-THEN-ELSE

-- simple construct
if logicalCondition then conditionWasTrue()
else conditionWasFalse()
 
-- multi-line is ok too
if logicalCondition
then
conditionWasTrue()
else
conditionWasFalse()
 
-- using block stuctures
if logicalCondition then do
conditionWasTrue()
...
end
else do
conditionWasFalse()
...
end
 
-- if/else if...
if logicalCondition1 then do
condition1WasTrue()
...
end
else if logicalCondition2 then do
condition2WasTrue()
...
end
else do
conditionsWereFalse()
...
end

[edit] SELECT

Notes: SELECT can be thought of as a better IF-THEN-ELSE construct.

Block structures (DO-END) can be used here too (see IF-THEN-ELSE).

OTHERWISE is optional but may result in run-time errors (netrexx.lang.NoOtherwiseException) if it isn't provided.

-- simple construct
select
when logicalCondition1 then condition1()
when logicalCondition2 then condition2()
otherwise conditionDefault()
end
 
-- set up a catch block to intercept missing OTHERWISE clause
do
select
when logicalCondition1 then condition1()
when logicalCondition2 then condition2()
end
catch ex1 = NoOtherwiseException
ex1.printStackTrace()
end

[edit] SELECT-CASE

-- simple construct
select case cc
when 'A' then say 'the case is A'
when 'B' then say 'the case is B'
otherwise say 'selection not recognized'
end

Note: This is functionally equivalent to:

select
when cc == 'A' then ...
when cc == 'B' then ...
...

[edit] SELECT Optional Features

SELECT has optional features (CATCH & FINALLY) and options (LABEL, PROTECT & CASE)

CATCH and FINALLY are used for handling exceptions thrown from inside the select group.

CASE see SELECT-CASE above.

LABEL provides a target for any LEAVE instructions and can aid in code self-documentation.

PROTECT is used for program concurrency & synchonization in multi-threaded programs.

select label sl protect cc case cc
when 'A' then do
say 'the case is A'
if logicalCondition then leave sl -- just to use the lable
say '...'
end
when 'B' then do
say 'the case is B'
say '...'
end
otherwise
say 'selection not recognized'
say '...'
catch exs = RuntimeException
say 'Gronk!'
exs.printStackTrace()
finally
say 'selection done'
say 'TTFN'
end sl

[edit] newLISP

[edit] if

Interpreter: newLISP v.9.0

(set 'x 1)
(if (= x 1) (println "is 1"))

A third expression can be used as an else.

(set 'x 0)
(if (= x 1) (println "is 1") (println "not 1"))

[edit] Nimrod

[edit] if-then-else

if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
boz()

[edit] case-of

case x
of 0:
foo()
of 2,5,9:
baz()
of 10..20, 40..50:
baz()
else: # All cases must be covered
boz()

[edit] Object Pascal

See Pascal

[edit] Objective-C

See also C

One difference: the preprocessor has been extended with an #import directive which does the same thing as #include with "include guards".

[edit] Objeck

[edit] if-else

 
a := GetValue();
if(a < 5) {
"less than 5"->PrintLine();
}
else if(a > 5) {
"greater than 5"->PrintLine();
}
else {
"equal to 5"->PrintLine();
};
 

[edit] select

 
a := GetValue();
select(a) {
label 5: {
"equal to 5"->PrintLine();
}
 
label 7: {
"equal to 7"->PrintLine();
}
 
other: {
"another value"->PrintLine();
}
};
 

[edit] OCaml

[edit] if-then-else

let condition = true
 
if condition then
1 (* evaluate something *)
else
2 (* evaluate something *)

If-then-else has higher precedence than ; (the semicolon), so if you want to have multiple statements with side effects inside an "if", you have to enclose it with begin...end or with parentheses:

if condition then begin
(); (* evaluate things for side effects *)
5
end
else begin
(); (* evaluate things for side effects *)
42
end

[edit] match-with

match expression with
| 0 -> () (* evaluate something *)
| 1 -> () (* evaluate something *)
| n when n mod 2 = 0 -> () (* evaluate something *)
| _ -> () (* evaluate something *)

The first | is optional, and usually omitted.

Match is especially useful for Pattern Matching on various types of data structures.

Nested match's need to be surrounded by begin-end or parentheses, or else it won't know where it ends.

[edit] Octave

if-then-elseif-else

if (condition)
% body
endif
 
if (condition)
% body
else
% otherwise body
endif
 
if (condition1)
% body
elseif (condition2)
% body 2
else
% otherwise body
endif

switch

switch( expression )
case label1
% code for label1
case label2
% code for label2
otherwise
% none of the previous
endswitch

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

switch ( x )
case 1
disp("it is 1");
case { 5,6,7 }
disp("it is 5, or 6 or 7");
otherwise
disp("unknown!");
endswitch


[edit] ooRexx

For all of the conditional instructions, the conditional expression must evaluate either to '1' or '0'. Note that ooRexx conditional expression evaluation does not have a short circuiting mechanism. Where the logical operations | (or), & (and), or && (exclusive or) are used, all parts of the expression are evaluated. The conditional 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,

if arg~isa(.string) & arg~left(1) == "*" then call processArg arg

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

if arg~isa(.string), arg~left(1) == "*" then call processArg arg

With this form, the second conditional expression is only evaluated if the first expression is true.

[edit] IF THEN --- IF THEN/ELSE

 
if y then x=6 /* Y must be either 0 or 1 */
 
 
if t**2>u then x=y
else x=-y
 
 
 
if t**2>u then do j=1 to 10; say prime(j); end
else x=-y
 
 
 
if z>w+4 then do
z=abs(z)
say 'z='z
end
else do; z=0; say 'failed.'; end
 
 
 
if x>y & c*d<sqrt(pz) |,
substr(abc,4,1)=='@' then if z=0 then call punt
else nop
else if z<0 then z=-y
 

[edit] SELECT WHEN

 
/*the WHEN conditional operators are the same as */
/*the IF conditional operators. */
 
select
when t<0 then z=abs(u)
when t=0 & y=0 then z=0
when t>0 then do
y=sqrt(z)
z=u**2
end
 
/*if control reaches this point and none of the WHENs */
/*were satisfiied, a SYNTAX condition is raised (error).*/
end
 

[edit] SELECT WHEN/OTHERWISE

 
select
when a=='angel' then many='host'
when a=='ass' | a=='donkey' then many='pace'
when a=='crocodile' then many='bask'
when a=='crow' then many='murder'
when a=='lark' then many='ascension'
when a=='quail' then many='bevy'
when a=='wolf' then many='pack'
otherwise say
say '*** error! ***'
say a "isn't one of the known thingys."
say
exit 13
end
 

[edit] OxygenBasic

 
if a then b=c else b=d
 
if a=0
b=c
elseif a<0
b=d
else
b=e
end if
 
select case a
case 'A'
v=21
case 'B'
v=22
case 1 to 64
v=a+300
case else
v=0
end select
 
 

[edit] Oz

[edit] if-then-else

proc {PrintParity X}
if {IsEven X} then
{Show even}
elseif {IsOdd X} then
{Show odd}
else
{Show 'should not happen'}
end
end

[edit] if-then-else as a ternary operator

fun {Max X Y}
if X > Y then X else Y end
end

[edit] case statement

fun {Fac X}
case X of 0 then 1
[] _ then X * {Fac X-1}
end
end

[edit] PARI/GP

GP uses a simple if statement:

if(condition, do_if_true, do_if_false)

and short-circuit && and || (which can be abbreviated & and | if desired).

PARI can use all of the usual C conditionals.

[edit] Pascal

[edit] if-then-else

IF condition1 THEN
procedure1
ELSE
procedure3;
 
IF condition1 THEN
BEGIN
procedure1;
procedure2;
END
ELSE
procedure3;
 
IF condition 1 THEN
BEGIN
procedure1;
procedure2;
END
ELSE
BEGIN
procedure3;
procedure4;
END;

[edit] case

Works with: Turbo Pascal version 7.0

Case selectors must be an ordinal type. This might seem to be a restriction, but with a little thought just about anything can be resolved to an ordinal type. Additionally, each selector may consist of more then one item. The optional ELSE keyword provides a default for values that do not match any of the given cases.

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.

case i of
1,4,9: { executed if i is 1, 4 or 9 }
DoSomething;
11, 13 .. 17: { executed if i is 11, 13, 14, 15, 16 or 17 }
DoSomethingElse;
42: { executed only if i is 42 }
DoSomeOtherThing;
else
DoYetAnotherThing;
end;

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

Case X of
'A' : statement ;
'B' : statement ;
in ['C'..'W'] : statement ;
else
Statement ;
end;

[edit] Perl

Works with: Perl version 5

[edit] if/else

if ($expression) {
    do_something;
};
# postfix conditional
do_something if $expression;
if ($expression) {
    do_something;
} else {
    do_fallback;
};
if ($expression1) {
    do_something;
} elsif ($expression2) {
    do_something_different;
} else {
    do_fallback;
};

[edit] unless

unless behaves like if, only logically negated. You can use it wherever you can use if. An unless block can have elsif and else blocks, but there is no elsunless.

[edit] ternary operator

This is the same as the if/else example, only less readable. But it returns the value of its executed branch.

$expression ? do_something : do_fallback;

[edit] logical operators

$condition and do_something is equivalent to $condition ? do_something : $condition.

$condition or do_something is equivalent to $condition ? $condition : do_something.

&& and || have the same semantics as and and or, respectively, but their precedence is much higher, making them better for conditional expressions than control flow.

[edit] switch

Works with: Perl version 5.10
use feature "switch";
given ($input) {
when (0) { print 'input == 0'; }
when ('coffee') { print 'input equal coffee'; }
when ([1..9]) { print 'input between 1 and 9'; }
when (/rats/) { print 'input matches rats'; }
default { do_fallback; }
}

[edit] Perl 6

[edit] if/else

if, else, elsif, unless, and given work much as they do in Perl 5, with the following differences:
  • All the parentheses are now optional.
  • unless no longer permits elsif or else blocks.
  • If the block of an if, elsif, or unless has a nonzero arity, the value of the conditional expression is used as an argument to the block:
    if won() -> $prize {
    say "You won $prize.";
    }
    If an else block has a nonzero arity, it receives the value of the condition tested by the last if or elsif.

[edit] given/when

Switch structures are done by topicalization and by smartmatching in Perl 6. They are somewhat orthogonal, you can use a given block without when, and vice versa. But the typical use is:

given lc prompt("Done? ") {
when 'yes' { return }
when 'no' { next }
default { say "Please answer either yes or not." }
}

when blocks are allowed in any block that topicalizes $_, including a for loop (assuming one of its loop variables is bound to $_) or the body of a method (if you have declared the invocant as $_)." See Synopsis 4.

There are also statement modifier forms of all of the above.

[edit] Ternary operator

The ternary operator looks like this:

$expression ?? do_something !! do_fallback

[edit] Other short-circuiting operators

and, or, &&, || and // work as in Perl 5.

[edit] PHL

If-else:

var a = 5;
if (a == 5) {
doSomething();
} else if (a > 0) {
doSomethingElse();
} else {
error();
}

[edit] PHP

[edit] if

Interpreter: PHP 3.x, 4.x, 5.x

<?php
 
$foo = 3;
 
if ($foo == 2)
//do something
 
if ($foo == 3)
//do something
else
//do something else
 
if ($foo != 0)
{
//do something
}
else
{
//do another thing
}
 
?>

[edit] switch

Interpreter: PHP 3.x & 4.x & 5.x

<?php
 
switch ($i)
{
case "apple":
echo "i is apple";
break;
 
case "bar":
echo "i is bar";
break;
 
case "cake":
echo "i is cake";
break;
}
 
?>

[edit] See Also

[edit] PicoLisp

[edit] Two-way conditions

(if (condition)                  # If the condition evaluates to non-NIL
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(and-more) )
 
(ifn (condition) # If the condition evaluates to NIL
(then-do-this) # Then execute the following expression
(else-do-that) # Else execute all other expressions
(and-more) )

One-way conditions

(when (condition)                # If the condition evaluates to non-NIL
(then-do-this) # Then execute tall following expressions
(and-more) )
 
(unless (condition) # If the condition evaluates to NIL
(then-do-this) # Then execute all following expressions
(and-more) )

[edit] Four-way condition

(if2 (condition1) (condition2)   # If both conditions evaluate to non-NIL
(expression-both) # Then execute this expression
(expression-first) # Otherwise this for the first
(expression-second) # or this the second condition.
(expression-none) # If both are NIL, all following expressions
(and-more) )

[edit] Multiple conditions

(cond
((condition1) # If this condition evaluates to non-NIL
(expression 1) # Execute these expression(s)
(more 1) )
((condition2) # Otherwise, if this evaluates to non-NIL
(expression 2) # Execute these expression(s)
(more 2) )
(T # If none evaluated to non-NIL
(expression 1) # Execute these expression(s)
(more 1) )
 
(nond
((condition1) # If this condition evaluates to NIL
(expression 1) # Execute these expression(s)
(more 1) )
((condition2) # Otherwise, if this evaluates to NIL
(expression 2) # Execute these expression(s)
(more 2) )
(NIL # If none evaluated to NIL
(expression 1) # Execute these expression(s)
(more 1) )

[edit] Selection

(case (expression)               # Evaluate the expression
(value1 # If it is equal to, or member of, 'value1'
(do-this1) # Execute these expression(s)
(do-that1) )
(value2 # Else if it is equal to, or member of, 'value2
(do-this2) # Execute these expression(s)
(do-that2) )
(T # Else execute final expression(s)
(do-something-else) ) )

[edit] PL/I

[edit] if-then-else

if condition_exp then unique_statement; else unique_statement;
 
if condition_exp then
unique_statement;
else
unique_statement;
 
if condition_exp
then do;
list_of_statements;
end;
else do;
list_of_statements;
end;

So a cascading form can be derived from:

if condition_exp1 then
statement_1;
else if condition_exp2 then
statement_2;
else if condition_expN then
statement_N;
else
statement_E;
 
if condition_exp1 then do;
list_of_statements;
end;
else if condition_exp2 then do;
list_of_statements;
end;
else if condition_expN then do;
list_of_statements;
end;
else do;
list_of_statements;
end;

[edit] case

The PL/I 'case' statement has two possible formats:

[edit] select - format 1

select (i); /* select on value of variable */
when (1,4,9)
do;
statement_s;
end;
 
when (11, 42)
do;
statement_s;
end;
 
other /* everything else */
do;
statement_s;
end;
end;

[edit] select - format 2

select; /* select first matching condition */
when (i = 4)
do;
statement_s;
end;
 
when (this = that)
do;
statement_s;
end;
 
when (mystring = 'ABCDE')
do;
statement_s;
end;
 
other
do;
statement_s;
end;
end;

Notes:

  • in PL/I there is no fall-through to the next when. When execution reaches the end of a matching clause, it continues after the end of the select statement, not in the code for the next case.
  • the do ... end statements can be omitted if the when clause is followed by a single statement.
  • if no other (or in full: otherwise) statement is present and none of the when cases is matched, the program will end in error.

[edit] Pop11

The simplest conditional is:

if condition then
 ;;; Action
endif;

Two way conditional looks like:

if condition then
 ;;; Action1
else
 ;;; Alternative action
endif;

One can do multiway choice using elseif clause

if condition1 then
 ;;; Action1
elseif condition2 then
 ;;; Action1
elseif condition2 then
 ;;; Action2
elseif condition3 then
 ;;; Action3
else
 ;;; Alternative action
endif;

Instead of if keyword one can use unless keyword.

unless condition then /* Action */ endunless;

has the same meaning as

if not(condition) then /* Action */ endif;

One can also use elseunless keword.

if condition1 then
 ;;; Action1
elseunless condition2 then
 ;;; Action2
endif;
 ;;; Action2
endif;

has the same meaning as

if condition1 then
 ;;; 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 middle one can mix elseif with elseunless.

Pop11 conditional is an expression:

if x > 0 then 1 elseif x < 0 then -1 else 0 endif -> sign_x ;

assigns sign of x to sign_x.

Instead of multiway if one can use switchon construct (which is equivalent to a special case of if, but may be shorter).

switchon(x)
case .isstring then printf('A1');
notcase .isinteger then printf('A2');
case = 2 orcase = 3 then printf('A3');
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 and loops (in case of loop exit/continue statements).

Pop11 also has preprocessor allowing conditional compilation:

#_IF condition1
/* Variant 1 */
#_ELSEIF condition2
/* Variant 2 */
#_ELSE
/* Variant 3 */
#_ENDIF

condition1 and condition2 are arbitrary Pop11 expressions (they have access to all previously compiled code).

Also note that Pop11 syntax is user extensible, so users may create their own conditional constructs.

[edit] PostScript

The "if" 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):

9 10 lt {(9 is less than 10) show} if

The "ifelse" operator expects two procedures and executes the one or the other depending on the value of the boolean. I.e. this:

/a 5 lt {(yeah)} {(nope)} ifelse show

will render either the string "yeah" or "nope" depending on whether a is less than 5 or not.

[edit] PowerShell

[edit] If, ElseIf, Else

# standard if
if (condition) {
# ...
}
 
# if-then-else
if (condition) {
# ...
} else {
# ...
}
 
# if-then-elseif-else
if (condition) {
# ...
} elseif (condition2) {
# ...
} else {
# ...
}

[edit] Switch

# standard switch
switch ($var) {
1 { "Value was 1" }
2 { "Value was 2" }
default { "Value was something else" }
}
 
# switch with wildcard matching
switch -Wildcard ($var) {
"a*" { "Started with a" }
"*x" { "Ended with x" }
}
 
# switch with regular expression matching
switch -Regex ($var) {
"[aeiou]" { "Contained a consonant" }
"(.)\1" { "Contained a character twice in a row" }
}
 
# switch allows for scriptblocks too
switch ($var) {
{ $_ % 2 -eq 0 } { "Number was even" }
{ $_ -gt 100 } { "Number was greater than 100" }
}
 
# switch allows for handling a file
switch -Regex -File somefile.txt {
"\d+" { "Line started with a number" }
"\s+" { "Line started with whitespace" }
}

[edit] PureBasic

Works with: PureBasic version 4.41

[edit] If, Elseif, Else

If a = 0
Debug "a = 0"
 
ElseIf a > 0
Debug "a > 0"
 
Else
Debug "a < 0"
 
EndIf

[edit] Select

Variable = 2
 
Select Variable
Case 0
Debug "Variable = 0"
 
Case 10, 11, 99
Debug "Variable is 10, 11 or 99"
 
Case 20 To 30
Debug "Variable >= 20 And Variable <= 30"
 
Default
Debug "Variable = something else..."
EndSelect

[edit] 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.

 
CompilerIf #PB_Compiler_OS = #PB_OS_Linux And #PB_Compiler_Processor = #PB_Processor_x86
Debug "Compiled on x86 Linux"
CompilerElse
Debug "Compiled on something else"
CompilerEndIf
 

[edit] CompilerSelect

 
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_Linux
Debug "Compiled on Linux"
CompilerCase #PB_OS_Windows
Debug "Compiled on Windows"
CompilerCase #PB_OS_MacOS
Debug "Compiled on Mac OS"
CompilerDefault
Debug "Compiled on something else"
CompilerEndIf
 

[edit] Python

[edit] if-then-else

if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
boz()

[edit] ternary expressions

Interpreter: Python 2.5

true_value if condition else false_value

Example:

>>> secret='foo'
>>> 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:

>>> secret = 'foo'
>>> result = 'got it' if secret=='foo' else 'try again'
>>> print result
'got it'

[edit] Function dispatch dictionary

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 = dict()
dispatcher[0]=foo # Not foo(): we bind the dictionary entry to the function's object,
# NOT to the results returned by an invocation of the function
dispatcher[1]=bar
dispatcher[2]=baz # foo,bar, baz, and boz are defined functions.
 
# Then later
results = dispatcher.get(x, boz)() # binding results to a name is optional
# or with no "default" case:
if x in dispatcher:
results=dispatcher[x]()
# The above, but with a dict literal
dispatcher = {
0: foo,
1: bar,
2: baz,
}
# ...
results = dispatcher.get(x, boz)()
# Or without the temp variable
# (it's up to the reader to decide how "pythonic" this is or isn't)
results = {
0: foo,
1: bar,
2: baz,
}.get(x, boz)()

This can be particularly handy when using currying techniques, or when lambda expressions or meta-function generators (factories) can be used in place of normal named functions.

In general a dispatch table or class/object abstraction (using dynamic method over-rides) is considered preferable to chains of if ... elif ... elif ... in Python programming.

[edit] Racket

[edit] if

If-expressions in Racket must have both branches

 
(if (< x 10)
"small"
"big")
 

[edit] 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"))
 

[edit] cond

Used for multiple conditions:

 
(printf "x is ~a\n"
(cond [(< x 1) "tiny"]
[(< x 10) "small"]
[(< x 100) "medium"]
[(< x 10000) "big"]
[(< x 100000000) "huge"]
[else "gigantic"]))
 

[edit] case

Similar to a "switch" statement in other languages

 
(case x
[(1) "one"]
[(2) "two"]
[(3) "three"]
[(4) "four"]
[(6 8) "even"]
[(5 7 9) "odd"]
[else "something else"])
 

[edit] etc

Racket has macros, which means that you can define whatever new conditional you think is useful...

[edit] Retro

[edit] if, ifTrue, and ifFalse

( condition ) [ ( true statements  ) ] ifTrue
( condition ) [ ( false statements ) ] ifFalse
( condition ) [ ( true statements ) ] [ ( false statements ) ] if

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

[edit] when

: foo ( n- )
[ 1 = ] [ drop ( if quote evaluates to true ) ] when
[ 2 = ] [ drop ( if quote evaluates to true ) ] when
[ 3 = ] [ drop ( if quote evaluates to true ) ] when
drop ( default action ) ;

[edit] REXX

[edit] IF--THEN, IF--THEN--ELSE

if  y  then x=6                        /* Y must be either   0   or   1 */
 
 
if t**2>u then x= y
else x=-y
 
 
if t**2>u then do j=1 to 10; say prime(j); end
else x=-y
 
 
if z>w+4 then do
z=abs(z)
say 'z='z
end
else do; z=0; say 'failed.'; end
 
 
if x>y & c*d<sqrt(pz) |,
substr(abc,4,1)=='@' then if z=0 then call punt
else nop
else if z<0 then z=-y

[edit] SELECT--WHEN

                     /*the  WHEN  conditional operators are the same as */
/*the IF conditional operators. */
select
when t<0 then z=abs(u)
when t=0 & y=0 then z=0
when t>0 then do
y=sqrt(z)
z=u**2
end
 
/*if control reaches this point and none of the WHENs */
/*were satisfied, a SYNTAX condition is raised (error).*/
end /*select*/

[edit] SELECT--WHEN/OTHERWISE

     select
when g=='angel' then many='host'
when g=='ass' | g=='donkey' then many='pace'
when g=='crocodile' then many='bask'
when g=='crow' then many='murder'
when g=='lark' then many='ascension'
when g=='quail' then many='bevy'
when g=='wolf' then many='pack'
otherwise say
say '*** error! ***'
say g "isn't one of the known thingys."
say
exit 13
end /*select*/

[edit] Rhope

Works with: Rhope version alpha 1

[edit] if-then-else

If[cond]
|:
Do Something[]
:||:
Do Something Else[]
:|

[edit] RLaB

[edit] if

Block of instructions following the if command has to be always enclosed in curly brackets.

 
if (x==1)
{
// do something
}
 

[edit] if-else

If there are branching within the command, respective blocks have to be enclosed in the blocks preceding it. Consider an example:

 
if (x==1)
{
// do something if x is 1
y = const.pi;
else
// do something if x is not 1
y = sin(const.pi*(1-x)) / (1-x);
}
 
 
if (x==1)
{
// do something if x is 1
y = const.pi;
else if (x == 2)
{
// do something if x is 2
y = sin(const.pi*(1-x)) / (1-x);
else
// do something in all the other cases
y = rand();
}}
 

[edit] Ruby

See Conditional Structures/Ruby

[edit] Run BASIC

' Boolean Evaluations
'
' > Greater Than
' < Less Than
' >= Greater Than Or Equal To
' <= Less Than Or Equal To
' = Equal to
 
x = 0
 
if x = 0 then print "Zero"
 
' --------------------------
' if/then/else
if x = 0 then
print "Zero"
else
print "Nonzero"
end if
 
' --------------------------
' not
if x then
print "x has a value."
end if
if not(x) then
print "x has no value."
end if
 
' --------------------------
' if .. end if
if x = 0 then
print "Zero"
goto [surprise]
end if
wait
 
if x = 0 then goto [surprise]
print "No surprise."
wait
 
[surprise]
print "Surprise!"
wait
 
' --------------------------
' case numeric
num = 3
 
select case num
case 1
print "one"
 
case 2
print "two"
 
case 3
print "three"
 
case else
print "other number"
 
end select
 
' --------------------------
' case character
var$="blue"
 
select case var$
 
case "red"
print "red"
 
case "green"
print "green"
 
case else
print "color unknown"
 
end select

[edit] Sather

    if EXPR then
-- CODE
elsif EXPR then
-- CODE
else
-- CODE
end;

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

    case EXPR
when EXPRL then
-- CODE
when EXPRL then
-- CODE
else
-- CODE
end;

EXPRL is a single expression or a comma-separated list of exressions. The expressions must evaluate to comparable objects (the method is_eq must be implemented)

[edit] Scala

Library: Scala
  if (n == 12) "twelve" else "not twelve"
 
today match {
case Monday =>
Compute_Starting_Balance;
case Friday =>
Compute_Ending_Balance;
case Tuesday =>
Accumulate_Sales
case _ => {}
}

[edit] Scheme

Procedures can be categorised as primitive or derived. Derived procedures can be defined in terms of primitive procedures.

[edit] Primitive

[edit] if

(if <test> <consequent> <alternate>)
(if <test> <consequent>)

Example:

(display
(if (> 1 2)
"yes"
"no"))
(newline)
(display
(if (> 1 2)
(- 1 2)))
(newline)
Output:
no
#<unspecified>

[edit] Derived

[edit] cond

(cond <clause1> <clause2> ...)

Example:

(display
(cond ((> 1 2) "greater")
((< 1 2) "less")))
(newline)
(display
(cond ((> 1 1) "greater")
((< 1 1) "less")
(else "equal")))
(newline)
Output:
less
equal

[edit] case

(case <key> <clause1> <clause2> ...)

Example:

(display
(case (* 2 3)
((2 3 5 7) "prime")
((1 4 6 8 9) "composite")))
(newline)
(display
(case (car (list c d))
((a e i o u) "vowel")
((w y) "semivowel")
(else "consonant")))
(newline)
Output:
composite
consonant

[edit] Scilab

[edit] if-then-else

if condition1 then instructions
[elseif conditioni then instructions]
....
[else instructions]
end

[edit] select-case

select expresion
  case expresion1 then instructions1
  [case expresion2 then instructions2]
  ...
  [case expresionn then instructions]
  [else instructions]
end

[edit] Seed7

[edit] if-then-else

There can be single or multiple statements. An if-statement can have multiple elsif parts.

if condition then
statement
end if;
 
if condition then
statement1
else
statement2;
end if;
 
if condition1 then
statement1
elsif condition2 then
statement2;
end if;
 
if condition1 then
statement1
elsif condition2 then
statement2;
else
statement3;
end if;

[edit] case

case i of
when {1, 4, 9}: # Executed if i is 1, 4 or 9
statement1;
when {11} | {13 .. 17}: # Executed if i is 11, 13, 14, 15, 16 or 17
statement2;
when {42}: # Executed only if i is 42
statement3;
otherwise:
statement4;
end case;

[edit] SIMPOL

[edit] if-else if-else

if x == 1
foo()
else if x == 2
bar()
else
foobar()
end if

[edit] ternary if function

.if(x == 1, "hello", "world")

[edit] Slate

[edit] ifTrue/ifFalse

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


[edit] caseOf:otherwise:

c@(Net URLPathEncoder traits) convert
[ | byte1 byte2 byte3 digit1 digit2|
[c in isAtEnd] whileFalse:
[byte1: c in next.
byte1 caseOf: {
$+ -> [c out nextPut: $\s].
$% -> [byte2: c in next.
byte3: c in next.
digit1: (byte2 toDigit: 16).
digit2: (byte3 toDigit: 16).
digit1 isNil \/ [digit2 isNil] ifTrue: [error: 'Error reading hex sequence after %'].
c out nextPut: (digit1 * 16 + digit2 as: c out elementType)].
} otherwise: [c out nextPut: byte1].
].
].

[edit] whileTrue:/whileFalse:

[p isAtEnd] whileFalse: [p next evaluate]].

[edit] Smalltalk

The pattern for handling a multi-option switch is to create classes for the various options, and let Polymorphism take care of the decisions.

[edit] ifTrue/ifFalse

"Conditionals in Smalltalk are really messages sent to Boolean objects"
balance > 0
ifTrue: [Transcript cr; show: 'still sitting pretty!'.]
ifFalse: [Transcript cr; show: 'No money till payday!'.].

You can also use them as the ternary operator

abs := x > 0 ifTrue: [ x ] ifFalse: [ x negated ]

[edit] SNOBOL4

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

	A = "true"
* "if-then-else"
if A "true" :s(goTrue)f(goFalse)
goTrue output = "A is TRUE" :(fi)
goFalse output = "A is not TRUE" :(fi)
fi
 
* "switch"
switch A ("true" | "false") . switch :s($("case" switch))f(default)
casetrue output = "A is TRUE" :(esac)
casefalse output = "A is FALSE" :(esac)
default output = "A is neither FALSE nor TRUE"
esac
end

[edit] SNUSP

$==?\==zero=====!/==#
\==non zero==/

? is the only conditional operator. It skips one character if the current cell is zero.

! is an unconditional skip. !/ is the idiom for joining two lines of execution. ?! inverts the test.

\ and / redirect the flow of control. All the other characters besides $ and # are commentary.


[edit] Sparkling

If statement:

var odd = 13;
if odd % 2 != 0 {
print("odd");
}

If-else statement:

var odd = 13;
if odd % 2 != 0 {
print("odd");
} else {
print("even");
}

If and if-else statements can be chained:

var nodiv3 = 13;
if nodiv3 % 3 == 0 {
print("divisible by 3");
} else if nodiv3 % 3 == 1 {
print("gives 1 remainder");
} else {
print("gives 2 remainder");
}

There's no "switch-case" statement in Sparkling yet, but it's work in progress.

[edit] SQL

Works with: MS SQL version 2005

[edit] Conditional Expression

CASE WHEN a THEN b ELSE c END
 
DECLARE @n INT
SET @n=124
print CASE WHEN @n=123 THEN 'equal' ELSE 'not equal' END
 
--If/ElseIf expression
SET @n=5
print CASE WHEN @n=3 THEN 'Three' WHEN @n=4 THEN 'Four' ELSE 'Other' END

[edit] If/Else

DECLARE @n INT
SET @n=123
IF @n=123
BEGIN --begin/end needed if more than one statement inside
print 'one two three'
END
ELSE
IF @n=124 print 'one two four'
ELSE print 'other'

[edit] Tcl

[edit] if-then-else

if {$foo == 3} {
puts "foo is three"
} elseif {$foo == 4} {
puts "foo is four"
} else {
puts "foo is neither three nor four"
}

or (using the ternary operator of expressions)

set result [expr { $foo == 3 ? "three" : "not three" }]

[edit] switch

switch -- $foo {
3 {puts "foo is three"}
4 {puts "foo is four"}
default {puts "foo is something else"}
}

Note that the switch command can also use glob matching (like case in the Bourne Shell) or regular-expression matching.

[edit] Toka

[edit] ifTrue

( condition ) ( quote ) ifTrue

100 100 = [ ." True\n" ] ifTrue
100 200 = [ ." True\n" ] ifTrue

[edit] ifFalse

( condition ) ( quote ) ifFalse

100 100 = [ ." True\n" ] ifFalse
100 200 = [ ." True\n" ] ifFalse

[edit] ifTrueFalse

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

100 100 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse
100 200 = [ ." Equal\n" ] [ ." Not Equal\n" ] ifTrueFalse

[edit] TorqueScript

[edit] if-then-else

// numbers and objects
if(%num == 1)
{
foo();
}
else if(%obj == MyObject.getID())
{
bar();
}
else
{
deusEx();
}
 
// strings
if(%str $= "Hello World")
{
foo();
}
else if(%str $= "Bye World")
{
bar();
}
else
{
deusEx();
}

[edit] switch

// numbers and objects
switch(%num)
{
case 1:
one();
case 2:
twoThreeOrFour();
case 3:
twoThreeOrFour();
case 4:
twoThreeOrFour();
case 5:
five();
case MyObject.getID():
anObject();
default:
everythingElse();
}
 
// strings
switch$(%str)
{
case "Hello":
arrival();
case "Goodbye":
departure();
default:
somethingElse();
}

[edit] conditional (ternary) operator (?:)

%formatted = %str @ ((getSubStr(%str,strLen(%str) - 1,1) $= "s") ? "'" : "'s");

[edit] Trith

[edit] branch

true ["yes" print] ["no" print] branch

[edit] when

true ["yes" print] when

[edit] unless

false ["no" print] unless


[edit] TUSCRIPT

[edit] IF ELSEIF ELSE ENDIF

 
$$ MODE TUSCRIPT
 
condition="c"
IF (condition=="a") THEN
---> do something
ELSEIF (condition=="b") THEN
---> do something
ELSE
---> do something
ENDIF
 

[edit] SELECT CASE DEFAULT ENDSELECT

 
$$ MODE TUSCRIPT
 
days="Monday'Tuesday'Wednesday'Thursday'Friday'Saturday'Sunday"
dayofweek=DATE (today,day,month,year,number)
day=SELECT (days,#dayofweek)
 
SELECT day
CASE "Monday"
---> do something
CASE "Saturday","Sunday"
---> do something
DEFAULT
---> do something
ENDSELECT
 

[edit] TXR

In TXR, most directives are conditionals, because they specify some kind of match. Given some directive D, the underlying logic in the language is, roughtly, "if D does not match at the current position in the input, then fail, otherwise the input advances according to the semantics of D".

An easy analogy to regular expressions may be drawn. The regex /abc/ means something like "if a doesn't match, then fail, otherwise consume a character and if b doesn't match, then fail, otherwise consume another character and if c doesn't match, then fail otherwise consume another character and succeed." The expressive power comes from, in part, not having to write all these decisions and book-keeping.

The interesting conditional-like structures in TXR are the parallel directives, which apply separate clauses to the same input, and then integrate the results in various ways.

For instance the choose 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
@(or)
@x<--@y
@(or)
@x+@y
@(end)

Suppose the input is something which can match all three patterns in different ways:

foo<--bar:baz+xyzzy

The outcome (with txr -B) will be:

x="foo"
y="bar:baz+xyzzy"

because this match minimizes the length of x. If we change this to :longest x, we get:

x="foo<--bar:baz"
y="xyzzy"

The cases, all and none directives most resemble control structures because they have short-circuiting behavior. For instance:

@(all)
@x:y@
@z<-@w
@(and)
@(output)
We have a match: (x, y, z, w) = (@x, @y, @z, @w).
@(end)
@(end)

If any subclause fails to match, then all 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:

@# match a line which contains some piece of text x
@# after the rightmost occurence of : such that the same piece
@# of text also occurs at the start of the line preceded by -->
@(all)
@*junk:@x
@(and)
-->@x@/.*/
@(end)
$ echo "-->asdfhjig:asdf" | txr -B weird.txr -
junk="-->asdfhjig"
x="asdf"
$ echo "-->assfhjig:asdf" | txr -B weird.txr -
false
$

[edit] UNIX Shell

Works with: Bourne Shell

[edit] If conditionals

The basic syntax is if command-list; then command-list; fi. If the first command list succeeds (by returning 0 for success), then the shell runs the second command list.

if test 3 -lt 5; then echo '3 is less than 5'; fi

[edit] Else and elif

There are optional elif (else if) and else clauses.

if test 4 -ge 6; then
echo '4 is greater than or equal to 6'
elif test 4 -lt 6; then
echo '4 is less than 6'
else
echo '4 compares not to 6'
fi

[edit] Switch conditionals

The Unix shell provides support for multibranch switch conditional constructs using the case statement:

case value in
choicea)
foo
 ;;
choiceb)
bar
 ;;
esac

[edit] Conditional branching using operators

One can also use && and || as conditional structures; see short-circuit evaluation#UNIX Shell.

test 3 -lt 5 && echo '3 is less than 5'
test 4 -ge 6 || echo '4 is not greater than or equal to 6'

[edit] Conditional loops

The Unix shell also supports conditional loops:

# This is a while loop
l=1
while [ l -le 5 ]; do
echo $l
done
 
# This is an until loop
l=1
until [ l -eq 5 ]; do
echo $l
done

[edit] C Shell

The single-line if syntax is if (expression) simple-command.

if (3 < 5) echo '3 is less than 5'
if ({ grep -q ^root: /etc/passwd }) echo 'passwd has root'

The multi-line if syntax has a then clause, and can have optional else if and else clauses. Each clause may contain multiple commands.

if (4 >= 6) then
echo '4 is greater than or equal to 6'
else if (4 < 6) then
echo '4 is less than 6'
else
echo '4 compares not to 6'
endif

[edit] V

[edit] ifThenElse

[true]
['is true' puts]
['is false' puts]
ifte
 
=is true

[edit] ifThen

[true]
['is true' puts]
if
=is true

[edit] When

3 [
[1 =] [1 *]
[2 =] [10 *]
[3 =] [100 *]
[4 =] [1000 *]
] when
 
=300

[edit] Choice

true
1 2
choice
 
=1
 
false
1 2
choice
 
=2

[edit] VBScript

[edit] if-then-else

Block form:

If condition1 Then
statement
End If
 
If condition1 Then
statement
ElseIf condition2 Then
statement
...
ElseIf conditionN Then
statement
Else
statement
End If
 

Line form:

If condition Then statement
 
If condition Then statement Else statement

[edit] select-case

Select Case Expression
Case Value1: statement
Case Value2: statement
...
Case ValueN: statement
Case Else: statement
End Select
 
Select Case Expression
Case Value1
statements
Case Value2
statements
...
Case ValueN
statements
Case Else
statements
End Select

[edit] Visual Basic .NET

[edit] if-then-else

Basic

Dim result As String, a As String = "pants", b As String = "glasses"
 
If a = b Then
result = "passed"
Else
result = "failed"
End If

Condensed

Dim result As String, a As String = "pants", b As String = "glasses"
 
If a = b Then result = "passed" Else result = "failed"
 
If a = b Then
result = "passed"
Else : result = "failed"
End If
 
If a = b Then : result = "passed"
Else
result = "failed"
End If

[edit] if-then-elseif

Dim result As String, a As String = "pants", b As String = "glasses"
 
If a = b Then
result = "passed"
ElseIf a <> b Then
result = "failed"
Else
result = "impossible"
End If

[edit] select-case-else

Dim result As String, a As String = "pants", b As String = "glasses"
 
Select Case a
Case b
result = "match"
Case a : result = "duh"
Case Else
result = "impossible"
End Select

[edit] inline-conditional

Imports Microsoft.VisualBasic
 
...
 
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

[edit] generic-inline-conditional

Works with: Visual Basic .NET version 8.0
Imports Microsoft.VisualBasic
 
...
 
Function IIf2(Of T)(ByVal condition As Boolean, ByVal truepart As T, ByVal falsepart As T) As T
If condition Then Return truepart Else Return falsepart
End Function
 
...
 
Dim result As String = IIf2("pants" = "glasses", "passed", "failed") ' type is inferred

[edit] generic-inline-conditional

Language Version: 9.0+

Dim result As String = If("pants" = "glasses", "passed", "failed") ' type is inferred

[edit] Vorpal

[edit] if-then-else

if(condition){
result = 'met'
}
else{
result = 'not met'
}

[edit] Wrapl

[edit] simple conditional

Conditionals in Wrapl are expressions. Either success or failure can be omitted from the expression.

condition => success // failure
condition => success
condition // failure

[edit] goal directed evaluation

Wrapl's goal directed evaluation can be used to control conditional execution. The select-right operator & 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.

condition & success

The sequence operator | 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.

condition | failure

[edit] X86 Assembly

[edit] 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.

 
if(i>1)
DoSomething
 
FailedSoContinueCodeExecution.
 

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
 

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

 
if(i>1)
DoSomething
else if(i<=1)
DoSomethingElse
FailedSoContinueCodeExecution
 

In this case, we can use our previous example as a skeleton.

 
cmp i, 1
jg _DoSomething
jle _DoSomethingElse
FailedSoContinueCodeExecution
 

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.

One last commonly used condition.

 
if(i==1)
DoSomething
else
DoSomethingElse
FailedSoContinueExecution
 

In this case, we'd do this.

 
cmp i, 1
je _DoSomething
jne _DoSomethingElse
FailedSoContinueExecution
 

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

[edit] XPL0

     if BOOLEAN EXPRESSION then STATEMENT
     if BOOLEAN EXPRESSION then STATEMENT else STATEMENT
     if BOOLEAN EXPRESSION then EXPRESSION else EXPRESSION
     case INTEGER EXPRESSION of
             INTEGER EXPRESSION, ... INTEGER EXPRESSION: STATEMENT;
             ...
             INTEGER EXPRESSION, ... INTEGER EXPRESSION: STATEMENT
             other STATEMENT
     case of
             BOOLEAN EXPRESSION, ... BOOLEAN EXPRESSION: STATEMENT;
             ...
             BOOLEAN EXPRESSION, ... BOOLEAN EXPRESSION: STATEMENT
             other STATEMENT

[edit] XSLT

The <xsl:if> element allows simple conditional processing.

<xsl:if test="condition">
<!-- executed if XPath expression evaluates to true -->
</xsl:if>

The <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements allow more general conditional processing.

<xsl:choose>
<xsl:when test="condition1">
<!-- included if condition1 evaluates to true (like C `if`) -->
</xsl:when>
<xsl:when test="condition2">
<!-- included if all previous conditions evaluated to false and
condition2 evaluates to true (like C `else if`) -->
</xsl:when>
<--
...
-->
<xsl:otherwise>
<!-- included if all previous conditions evaluated to false
(like C `else`) -->
<!-- (The `otherwise` element is optional) -->
</xsl:otherwise>
</xsl:choose>

The XPath expressions in the test attribute are evaluated in boolean context (converted as if by the boolean function if necessary).

<xsl:if test="@attrib = 'foo'">...</xsl:if>
<xsl:if test="position() != last()">...</xsl:if>
<xsl:if test="not(false())">...</xsl:if>
 
<!-- Some XPath expressions must be escaped. -->
<xsl:if test='contains(node, "stuff") and (position() &gt; first())'>...</xsl:if>
 
<!-- The following two examples are synonymous because the test attribute is
implicitly converted to boolean. -->
<xsl:if test="boolean($expr)">...</xsl:if>
<xsl:if test="$expr">...</xsl:if>

[edit] zkl

if (x) y else z;
if(a)b else if (c) else d; etc
x:=(if (a) b else c);
 
a and b or c // usually the same as if(a) b else c, beware if b evals to False
 
switch(x){
case(1){...}
case("2"){...} // matches anything
case(a)[fallthrough]{...} // no break, no break has to be explicit
case(b){...}
else {...} // case a C's default, has to be at the end
}
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox