Conditional Structures

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.
Control Structures

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

Here, we document the conditional structures offered by different programming languages. Common conditional structures are if-then-else and switch.

Contents

[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

 
 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;
 

[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] ALGOL 68

[edit] IF ~ THEN ~ ELSE ~ FI clause

main: (
  INT input := 2;

  IF  3 = input THEN
    # Do something #
  FI;

  IF  3 = input THEN
    # Do something #
  ELSE 
    # Do something ELSE #
  FI
)

One line predicates do not any braces:

 IF cond THEN
   ~
 FI;
 IF cond THEN
   ~
 ELSE
   ~
 FI;

And these may be mixed:

 IF cond THEN
   ~
   IF cond THEN
     # multiple expressions #
   ELSE
     ~
   FI;
   ~
 FI

Or merged:

 IF cond1 THEN
   ~
 ELIF cond2 THEN
   # multiple expressions #
 ELSE
   ~
 FI # etc #

[edit] Short-circuit conditionals

The short-circuit evaluation of the ANDIF and ORELSE boolean operators are also often used for control flow.

IF node /= NULL ANDIF next OF node /= NULL ANDIF guarded_test(node) THEN
   next OF node := next OF next OF node
FI

Note that these are not part of the standard library and had to be defined by the user.

Neither the assignment nor guarded_test() will be called IF the previous two conditions aren't met. Other languages such as Pascal don't make that guarantee, and they certainly could not be user defined.

[edit] CASE ~ IN ~ OUT ~ ESAC clause

main: (
  INT input := 42;

  CASE input IN
      ~ # Do something, because input = 1 #
    ,
      ~ # Do something, because input = 2 #
    ,
      ~ # Do something, because input = 3 #
    ,
      # fall through to the next statement IF there is no "OUT" #
    OUT
      ~ # Do something ELSE. #
  CASE
)

The "CASE ~ IN ~ OUT ~ ESAC" is directly interchangeable with the "( ~ | ~ | ~ )", hence the above may be written as follows:

main: (
  INT input := 42;

  ( input |
      ~ # Do something, because input = 1 #
    ,
      ~ # Do something, because input = 2 #
    ,
      ~ # Do something, because input = 3 #
      # fall through to the next statement IF there is no "OUT" #
    |
      ~ # Do something ELSE. #
  )
)

Case statements may also be merged:

main:(
  INT a1, a2, b1, b2, c99;
  CASE 99 IN
    a1,
    a2
  OUSE 99 IN
    b1,
    b2
  OUT
    c99
  ESAC := 333
)

In this case a1, a2, b1 and b2 remain undefined, but c99 ends up being half-evil.

[edit] Ternary ( ~ | ~ | ~ )

Conditionals in C can also be done with the ternary operator, ?:. ALGOL 68 has the "brief" equivalents ( ~ | ~ | ~ )

main : (
  INT input := 2;
  INT output := (input = 2 | 42 | 4711);  # sets output to 42 #
  INT output2 := (input = 3 | 42 | 4711); # sets output2 to 4711 #

  PROC do_something = INT: random;
  PROC do_something_else = INT: random;
  input := (TRUE | do_something | do_something_else); # only calls do_something_else() #
)

The "( ~ | ~ | ~ )" is directly interchangeable with the "IF ~ THEN ~ ELSE ~ FI" syntax. Hence the above could be written:

main : (
  INT input := 2;
  INT output := IF input = 2 THEN 42 ELSE 4711 FI;  # sets output to 42 #
  INT output2 := IF input = 3 THEN 42 ELSE 4711 FI; # sets output2 to 4711 #

  PROC do_something = INT: random;
  PROC do_something_else = INT: random;
  input := IF TRUE THEN do_something ELSE do_something_else FI; # only calls do_something_else() #
)

A more complext example created by combining the above:

main: (
  INT x,y,z;
  CASE 2 IN x,y OUT z ESAC := IF 1+2=2 THEN 333 ELSE 666 FI
) 

In the result y becomes half-evil, with x and z remaining undefined.

[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] BASIC

Works with: QuickBasic version 4.5

[edit] if-then-else

Ifs can work with equality

IF something = somethingElse THEN
   'do stuff
ELSE IF something =someOtherThing THEN
   'do other stuff
ELSE
   'do more stuff
END IF

Or like in #C

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

[edit] select case

SELECT CASE variable
CASE value1
   'do stuff
CASE value2
   'do other stuff
CASE ELSE
   'default case
END SELECT

[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] 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] C

[edit] if-then-else

Works with: gcc version 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 */
  }
}

One line predicates do not require curly braces (although their usage is always preferred for readability):

 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;

[edit] Short-circuit conditionals

The short-circuit evaluation of the && and || boolean operators are also often used for control flow.

if (node != NULL && node->next != NULL && guarded_test(node))
   node->next = node->next->next;

Neither the assignment nor guarded_test() will be called if the previous two conditions aren't met. Other languages such as Pascal don't make that guarantee.

[edit] switch

Works with: gcc version 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 */
      /* fall through to the next statement if there is no "break" */
    default:
      /* Do something else. */
      break; /* Optional */
  }
}

A little known fact is that the default branch need not be the last one:

int main(int argc, char* argv[])
{
  switch (argc)
  {
  default:
    /* this will be executed if argc is neither 2 nor 3 */
    break;
  case 2:
    /* this will be executed if argc is 2 */
    break;
  case 3:
    /* this will be executer if argc is 3 */
  }
}

[edit] Ternary ?:

Works with: gcc version 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 argc, char ** argv)
{
  int input = 2;
  int output = (input == 2? 42 : 4711);  /* sets output to 42 */
  int output2 = (input == 3? 42 : 4711); /* sets output2 to 4711 */

  int do_something();
  int do_something_else();
  input == 1? do_something() : do_something_else(); /* only calls do_something_else() */
}

[edit] Preprocessor Techniques (compile-time)

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 thing this code does is define that macro, so that the next time the header is included, the code will be ignored. This effectively avoids multiple inclusion.

[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] 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] 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] 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 false.
 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] Delphi

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] 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 (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] 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] 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] Java

[edit] if-then-else

   if(s.equals("Hello World"))
   {
       foo();
   }
   else if(s.equals("Bye World"))
   {
       bar();
   }
   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.

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

   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 operator (?:)

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

[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";
 }

[edit] Logo

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

UCBLogo and its descendants have also case:

make "letter "e
show case :letter [ [[a e i o u] "true] [else "false] ]
make "letter "x
show case :letter [ [[a e i o u] "true] [else "false] ]

Output is:

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

[edit] if-then-else

Compiler: OCaml 3.09

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

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

[edit] case

Works with: Turbo Pascal version 7.0


In Pascal there's no fall-through, that is, if execution reaches the end of any case, execution continues after the end of the case statement, not in the code for the next case. Pascal implements the ELSE operator for all cases that do not match any of the given cases. 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 with a bit of imagination. Additionally, each item in the case may consist of more then one item.

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.

[edit] ternary operator

This is the same as the if/else example, only less readable.

$expression ? do_something : do_fallback;

[edit] switch

Switches are usually implemented with if chains as shown above. The for topicaliser, however, is great if you're going to do a lot of matching. Use next to avoid fall-through.

for ($input) {
    $_ == 0 and print 'zero';
    $_ eq 'coffee' and print 'C8H10N4O2';
    print 'small' if 1 <= $_ and $_ <= 9 ;
    /rats/ and print 'eek!';
    do_fallback;
};

The Switch module is a funky source filter and rewrites the syntax on the fly, which has got a bad reputation.

use Switch;
switch ($input) {
    case 0          {print 'input == 0'};
    case 'coffee'   {print 'input equal coffee'};
    case [1..9]     {print 'input between 1 and 9'};
    case /rats/     {print 'input matches rats'};
    else {
        do_fallback;
    };
};

[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] 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] Python

[edit] if-then-else

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

[edit] ternary

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'

[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
dispatcher['default']=boz
# Then later
results = dispatcher.get(x, 'default')()  # binding results to a name is optional
# or with no "default" case:
if x in dispatcher:
    results=dispatcher[x]()

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

[edit] Rhope

Works with: Rhope version alpha 1

[edit] if-then-else

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

[edit] Ruby

[edit] if-then-else

if s == 'Hello World'
  foo
elsif s == 'Bye World'
  bar
else
  deus_ex
end


[edit] case-when-else

case cartoon_character
when 'Tom'
  chase
when 'Jerry'
  flee
else
  nil
end

[edit] ternary

s == 'Hello World' ? foo : bar


[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] 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] 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"
 }

[edit] switch

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


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


[edit] generic-inline-conditional

Language Version: 9.0+

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

[edit] VBScript

[edit] if-then-else

if (condition) then 
   result = "met"
else
   Result = "not met"
end if

[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">
    <!-- executed if condition1 evaluates to true -->
  </xsl:when>
  <xsl:when test="condition2">
    <!-- executed if condition2 evaluates to true -->
  </xsl:when>
  <-- etc. -->
  <xsl:otherwise>
    <!-- optional catch-all processing, like C's else or default -->
  </xsl:otherwise>
</xsl:choose>

The XPath expressions allowed for the "test" attribute are those which return a boolean value:

@attrib = 'false'
position() != last()
not( false() )
boolean( $param )
contains( node, "stuff" ) and (position() > first())
Personal tools