Conditional structures
You are encouraged to solve this task according to the task description, using any language you may know.
Here, we document the conditional structures offered by different programming languages. Common conditional structures are if-then-else and switch.
ActionScript
if-else if-else
if(strVar=='value' && boolVar) { // test a string variable and a boolean variable // using the logical AND operator } else if(numVar1==100 || numVar2) { // test a number variable for a specific value // and another number variable (if numVar2 is 0, // the condition will evaluate to false) using // the logical OR operator } else { // do something }
"inline" if-else (conditional operator)
var myVar:String = (myOtherVar=='ok') ? 'the value is ok' : 'the value is NOT ok'; // usage is as follows: condition ? value-if-true : value-if-false;
switch
// string switch statement switch(strVar) { case 'one': // do something break; case 'two': // do something break; default: // the default action; } // number switch statement switch(numVar) { case 1: // do something break; case 2: // do something break; default: // the default action; }
Ada
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;
case
type Days is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday); Today : Days;
case Today in when Saturday | Sunday => null; when Monday => Compute_Starting_Balance; when Friday => Compute_Ending_Balance; when Others => Accumulate_Sales; end case;
AppleScript
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
C
if-then-else
Compiler: GCC 4.1.2
int main (int argc, char ** argv) { int input = 2; if ( 3 == input ) { // Do something } if ( 3 == input ) { // Do something } else { // Do something else } }
switch
Compiler: GCC 4.1.2
int main (int argc, char ** argv) { int input = 42; switch (input) { case 0: // Do something, because input = 0 break; case 1: // Do something, because input = 1 break; case 2: // Do something, because input = 2 default: // Do something else. break; // Optional } }
C++
Run-Time Control Structures
if-then-else
Compiler: GCC 4.1.2
int main (void) { int input = 2; if ( 3 == input ) { // Do something }
if ( 3 == input ) { // Do something } else { // Do something else } }
One line predicates do not require curly braces:
if(cond) expr;
if(cond) expr; else expr;
And these may be mixed:
if(cond) expr; else { // multiple expressions }
if(cond) { // multiple expressions } else expr;
?:
Compiler: GCC 4.0.2
Conditionals in C++ can also be done with the ternary operator, ?:. The arguments are expressions, and a?b:c is an expression as well. However, since many things in C++ are expressions (this especially includes assignments and function calls), ?: can be used for those, too. However, the if/else construct is usually more readable and therefore preferred.
int main() { int input = 2; int output = (input == 2? 42 : 4711); // sets output to 42 int output2 = (input == 3? 42 : 4711); // sets output2 to 4711 void do_something(); void do_something_else(); input == 1? do_something() : do_something_else(); // only calls do_something_else() }
switch
Compiler: GCC 4.1.2
int main (void) { int input = 42; switch (input) { case 0: // Do something, because input = 0 break; case 1: // Do something, because input = 1 break; case 2: // Do something, because input = 2 // Because there is no 'break', we also fall through // into the default case, executing it right after case 2: default: // Do something else. break; // Optional } }
Compile-Time Control Structures
Preprocessor Techniques
Conditional compile based on if a certain macro exists,
#ifdef FOO // compile this only if macro FOO exist #endif
Conditional compile based on if a macro doesn't exist
#ifndef FOO // only compiled if macro FOO does not exist #endif
Conditional compile based on if a certain macro exists, with else clause
#ifdef FOO // compile this only if macro FOO exist #else // compile this only if macro FOO does not exist #endif
Conditional compile based on expression
#if defined(FOO) && FOO == 1 // only compiled if macro FOO is defined and expands to a constant expression evaluating to 1 #endif
Chain of conditionals
#if defined(FOO) // only compiled if macro FOO is defined #elif defined(BAR) // only compiled if macro FOO is not defined, but macro BAR is #else // only compiled if neither FOO nor BAR is defined #endif
Typical usage: Include guards
#ifndef FOO_H_ALREADY_INCLUDED #define FOO_H_ALREADY_INCLUDED // header content #endif
If the header is included the first time, the macro FOO_H_ALREADY_INCLUDED will not be defined, thus the code between #ifndef and #endif will be compiled. The first thig this code does is to define that macro, so that the next time the header is included, the code will be ignored. This effectively avoids multiple inclusion.
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
ColdFusion
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>
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>
Forth
IF-ELSE
( condition ) IF ( true statements ) THEN ( condition ) IF ( true statements ) ELSE ( false statements ) THEN
example:
DUP 10 < IF ." Less than 10" ELSE ." Greater than or equal to 10" THEN
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 ;
IDL
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]
while
while a lt 5 print, "the next a will be ", ( a += 1 )
(Or expand the print statement into a begin ... end)
repeat
repeat <command or {begin..end} pair> until <condition>
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)
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.
on_error
on_error label
Will resume execution at label when an error is encountered. on_ioerror is similar but for IO errors.
Java
if-then-else
if(s.equals("Hello World")) { foo(); } else if(s.equals("Bye World")) { bar(); } else { deusEx(); }
ternary
s.equals("Hello World") ? foo : bar
switch
switch(c) { case 'a': foo(); break; case 'b': bar(); default: foobar(); }
JavaScript
if-then-else
if( s == "Hello World" ) { foo(); } else if( s == "Bye World" ) { bar(); } else { deusEx(); }
switch
switch(object) { case 1: one(); break; case 2: case 3: case 4: twoThreeOrFour(); break; case 5: five(); break; default: everythingElse(); }
conditional operator (?:)
var num = window.obj ? obj.getNumber() : null;
newLISP
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"))
OCaml
if-then-else
Compiler: OCaml 3.09
let condition = true if condition then ()//do something else ()//do something else
match-with
match expression with | 0 -> ()//do something | 1 -> ()//do something | n when n mod 2 = 0 -> ()//do something | _ -> ()//do something
Pascal
if-then-else
Compiler: Turbo Pascal 7.0
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;
Perl
if-then-else
Interpreter: Perl 5.8.8
#!/usr/bin/perl -w use strict; my $condition1 = 0; my $condition2 = 1; if ( $condition1 ) { # Do something } # post-conditional if do_something() if $condition1;
#!/usr/bin/perl -w use strict; my $condition1 = 0; my $condition2 = 1; if ( $condition1 ) { # Do something } elsif ( $condition2 ) { # Do somethine else }
#!/usr/bin/perl -w use strict; my $condition1 = 0; my $condition2 = 1; if ( $condition1 ) { # Do something } else { # Do something else }
#!/usr/bin/perl -w use strict; my $condition1 = 0; my $condition2 = 1; if ( $condition1 ) { # Do something } elsif ( $condition2 ) { # Do something else } else { # Do that other thing }
($condition) ? print "Then\n" : print "Else\n"; # or my $var = ($condition) ? "Then" : "Else";
unless
Interpreter: Perl 5.8.8
#!/usr/bin/perl -w use strict; my $condition1 = 0; unless ( $condition1 ) { # Do something }
# post-conditional unless do_something() unless $condition1; unless ( $condition1 ) { # Do something } else { # Do something else }
switch
Interpreter: Perl 5.8.8
#!/usr/bin/perl -w use strict; use Switch; $input = 42; switch ($input) { case 0 { # Do something, because input = 0 } case 1 { # Do something, because input = 1 } case "coffee" { # Do something, because input = coffee } else { # Do something else. } }
goto
Interpreter: Perl 5.8.8
Typically dispised by most Perl programmers
goto LABELB; LABELA: # note labels end with a colon not semi-colon goto END; LABELB: goto LABELA; END: exit(0);
PHP
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 } ?>
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; } ?>
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.
Python
if-then-else
if x == 0: foo() elif x == 1: bar() elif x == 2: baz() else: boz()
ternary
Interpreter: Python 2.5
True if True else False
Ruby
if-then-else
if s == 'Hello World' foo elsif s == 'Bye World' bar else deus_ex end
case-when-else
case cartoon_character when 'Tom' chase when 'Jerry' flee else nil end
ternary
s == 'Hello World' ? foo : bar
Smalltalk
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!'.].
Tcl
if-then-else
if {$foo == 3} { puts "foo is three" } else { puts "foo is not three" }
switch
switch $foo { 3 {puts "foo is three"} 4 {puts "foo is four"} default {puts "foo is something else"} }
Visual Basic .NET
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
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
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
inline-conditional
Imports Microsoft.VisualBasic ... Dim result As String = CType(IIf("pants" = "glasses", "passed", "failed"), String)
generic-inline-conditional
Compiler: Microsoft (R) Visual Basic Compiler 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