Conditional (programming)

From formulasearchengine
Jump to navigation Jump to search

In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.

In imperative programming languages, the term "conditional statement" is usually used, whereas in functional programming, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.

Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime.


The if–then construct (sometimes called if–then–else) is common across many programming languages. Although the syntax varies quite a bit from language to language, the basic structure (in pseudocode form) looks like this: (The example is actually perfectly valid Visual Basic or QuickBASIC syntax.)

 If (boolean condition)
 End If

When an interpreter finds an If, it expects a boolean condition – for example, x > 0, which means "the variable x contains a number that is greater than zero" – and evaluates that condition. If the condition is true, the statements following the then are executed. Otherwise, the execution continues in the following branch – either in the else block (which is usually optional), or if there is no else branch, then after the end If.

After either branch has been executed, control returns to the point after the end If.

In early programming languages, especially some dialects of BASIC in the 1980s home computers, an if–then statement could only contain GOTO statements. This led to a hard-to-read style of programming known as spaghetti programming, with programs in this style called spaghetti code. As a result, so called structured programming which allows (virtually) arbitrary statements to be put in statement blocks inside an if statement, gained in popularity, until it became the norm even in most BASIC programming circles. Such mechanisms and principles were based on the older but more advanced ALGOL family of languages, and ALGOL-like languages such as Pascal and Modula-2 influenced modern BASIC variants for many years. While it is possible while using only GOTO statements in if-then statements to write programs that are not spaghetti code and are just as well structured and readable as programs written in a structured programming language, so called structured programming makes this easier and enforces it. Structured if-then-else statements like the example above are one of the key elements of structured programming, and they are present in most popular high-level programming languages including C, its derivatives (including C++ and C#), Java, JavaScript and Visual Basic (all versions including .NET).

Else if

By using else if, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped. The statements of

if condition then
    -- statements;
elsif condition then
    -- more statements
elsif condition then
    -- more statements;
    -- other statements;
end if;

elsif, in Ada, is simply syntactic sugar for else followed by if. In Ada, the difference is that only one end if is needed, if one uses elsif instead of else followed by if.

In some other languages, such as C and Java, else if literally just means else followed by if, and syntactic sugar is neither needed nor provided. This works because in these languages, an else followed by one statement (in this case the if) does not need braces. This is not true in Perl, which provides the keyword elsif to avoid the large number of braces that would be required by multiple if and else statements. Similarly, Python uses the special keyword elif because structure is denoted by indentation rather than braces, so a repeated use of else and if would require increased indentation after every condition.

C and Java implementations, however, do have a disadvantage that each else if branch is, effectively, adding an extra nesting level, which will complicate compiler's writer job if arbitrarily long else if chains are to be supported.

If expressions

Many languages support if expressions, which are similar to if statements, but return a value as a result. Thus, they are true expressions (which evaluate to a value), not statements (which just perform an action).

As a ternary operator


In C and C-like languages conditional expressions take the form of a ternary operator called the conditional expression operator, ?:, which follows this template:

(condition)?(evaluate if condition was true):(evaluate if condition was false)

This means that conditions can be inlined into expressions, unlike with if statements, as shown here using C syntax:

//Invalid in most programming languages. Two of the exceptions are Ruby and Scala
my_variable = if(x > 10) { "foo" } else { "bar" };
my_variable = (x > 10)?"foo":"bar";

To accomplish the same as the second (correct) line above, using a standard if/else statement, this would take more than one line of code (under standard layout conventions):

if (x > 10)
  my_variable = 'foo';
  my_variable = 'bar';

The explicit if/then statement is easier to read and usually compiles more efficiently than the ternary operator.[1]

ALGOL 60 and some other members of the ALGOL family have the if expression which performs the same function.


  myvariable := if x > 10 then 1 else 2

In the Lisp dialects Scheme and Common Lisp, the former of which was inspired to a great extent by ALGOL:

 ;; Scheme
 (define myvariable (if (> x 10) 1 2))   ; Assigns ‘myvariable’ to 1 or 2, depending on the value of ‘x’

 ;; Common Lisp
 (let ((x 5))
   (setq myvariable (if (> x 10) 1 2)))  ; Assigns ‘myvariable’ to 2

As a function

In Visual Basic and some other languages, a function called IIf is provided, which can be used as a conditional expression. However, it does not behave like a true conditional expression, because both the true and false branches are always evaluated; it is just that the result of one of them is thrown away, while the result of the other is returned by the IIf function.

In Haskell

In Haskell 98, there is only an if expression, no if statement, and the else part is compulsory, as every expression must have some value.[2] Logic that would be expressed with conditionals in other languages is usually expressed with pattern matching in recursive functions.

Because Haskell is lazy, it is possible to write control structures,. such as if, as ordinary expressions; the lazy evaluation means that an if function can evaluate only the condition and proper branch (where a strict language would evaluate all three). It can be written like this:[3]

 if' :: Bool -> a -> a -> a
 if' True x _ = x
 if' False _ y = y

Arithmetic if

Up to Fortran 77, the language Fortran has an "arithmetic if" statement which is halfway between a computed IF and a case statement, based on the trichotomy , , . This was the earliest conditional statement in Fortran. [4]:

IF (e) label1, label2, label3

Where e is any numeric expression (not necessarily an integer); this is equivalent to

IF (e .LT. 0) GOTO label1
IF (e .EQ. 0) GOTO label2
IF (e .GT. 0) GOTO label3

Because this arithmetic IF is equivalent to multiple GOTO statements, it is considered to be an unstructured control statement, and should not be used if more structured statements can be used. In practice it has been observed that most arithmetic IF statements referenced the following statement with one or two of the labels.

This was the only conditional control statement in the original implementation of Fortran on the IBM 704 computer. On that computer it could be implemented quite efficiently using instructions such as 'Branch if accumulator negative'.

Object-oriented implementation in Smalltalk

In contrast to other languages, in Smalltalk the conditional statement is not a language construct but defined in the class Boolean as an abstract method that takes two parameters, both closures. Boolean has two subclasses, True and False, which both define the method, True executing the first closure only, False executing the second closure only.[5]

var = condition 
    ifTrue: [ 'foo' ]
    ifFalse: [ 'bar' ]

Case and switch statements


Switch statements (in some languages, case statements or multiway branches) compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action ('else','otherwise') to be taken if no match succeeds. Switch statements can allow compiler optimizations, such as lookup tables. In dynamic languages, the cases may not be limited to constant expressions, and might extend to pattern matching, as in the shell script example on the right, where the '*)' implements the default case as a regular expression matching any string.

Pascal: C: Java: Shell script:
case someChar of
  'a': actionOnA;
  'x': actionOnX;
  else actionOnNoMatch;
switch (someChar) {
  case 'a': actionOnA; break;
  case 'x': actionOnX; break;
  case 'y':
  case 'z': actionOnYandZ; break;
  default: actionOnNoMatch;
switch (age) {
  case 1: System.out.printf("You're one."); break;
  case 2: System.out.printf("You're two."); break;
  case 3: System.out.printf("You're three."); break;
  case 4: System.out.printf("You're four."); break;
  default: System.out.printf("You're neither!"); break;
case $someChar in 
   a)    actionOnA; ;;
   x)    actionOnX; ;;
   [yz]) actionOnYandZ; ;;
  *)     actionOnNoMatch  ;;

Pattern matching


Pattern matching may be seen as a more sophisticated alternative to both if-then-else, and case statements. It is available in many programming languages with functional programming features, such as ML and many others. Here is a simple example written in the OCaml language:

 match fruit with
 | "apple" -> cook pie
 | "coconut" -> cook dango_mochi
 | "banana" -> mix;;

The power of pattern matching is the ability to concisely match not only actions but also values to patterns of data. Here is an example written in Haskell which illustrates both of these features:

 map _ []      = []
 map f (h : t) = f h : map f t

This code defines a function map, which applies the first argument (a function) to each of the elements of the second argument (a list), and returns the resulting list. The two lines are the two definitions of the function for the two kinds of arguments possible in this case – one where the list is empty (just return an empty list) and the other case where the list is not empty.

Pattern matching is not strictly speaking always a choice construct, because it is possible in Haskell to write only one alternative, which is guaranteed to always be matched – in this situation, it is not being used as a choice construct, but simply as a way to bind names to values. However, it is frequently used as a choice construct in the languages in which it is available.

Branch predication


In assembly language, branch predication is a feature of certain central processing unit (CPU) instruction sets which permits conditional execution of instructions, without having to perform costly conditional jumps.

Choice system cross reference

This table refers to the most recent language specification of each language. For languages that do not have a specification, the latest officially released implementation is referred to.

Programming language Structured if switch/select/case Arithmetic if Pattern matching[A]
then else else-if
Template:Rh| Ada Yes Yes Yes Yes No No
Template:Rh| C/C++ Yes Yes unneeded[B] fall-through No No
Template:Rh| C# Yes Yes unneeded[B] Yes No No
Template:Rh| Eiffel Yes Yes Yes Yes No No
Template:Rh| F# Yes Yes Yes unneeded[C] No Yes
Template:Rh| FortranTemplate:Clarify Yes Yes Yes Yes Yes No
Template:Rh| Haskell Yes needed unneeded[B] unneeded[C] No Yes
Template:Rh| Java Yes Yes unneeded[B] fall-through[6] No No
Template:Rh| ECMAScript (JavaScript) Yes Yes unneeded[B] fall-through[7] No No
Template:Rh| Oberon Yes Yes Yes Yes No No
Template:Rh| Perl Yes Yes Yes Yes No No
Template:Rh| PHP Yes Yes Yes fall-through No No
Template:Rh| Pascal, Delphi Yes Yes unneeded Yes No No
Template:Rh| Python Yes Yes Yes No No No
Template:Rh| QuickBASIC Yes Yes Yes Yes Yes No
Template:Rh| Ruby Yes Yes Yes Yes No No
Template:Rh| Visual Basic, classic Yes Yes Yes No
Template:Rh| Visual Basic .NET Yes Yes Yes Yes No No
Template:Rh| Windows PowerShell Yes Yes Yes fall-through No No
  1. ^ This refers to pattern matching as a distinct conditional construct in the programming language – as opposed to mere string pattern matching support, such as regular expression support.
  2. 1 2 3 4 5 The often-encountered else if in the C family of languages, and in Haskell, is not a language feature but a set of nested and independent if then else statements combined with a particular source code layout. However, this also means that a distinct else-if construct is not really needed in these languages.
  3. 1 2 In Haskell and F#, a separate constant choice construct is unneeded, because the same task can be done with pattern matching.

See also



External links

  • Coding samples and links to user documentation in many languages: ActionScript, Assembly, Bash, BASIC, C, C++, C#, Excel, Fortran, Java, JavaScript, JSP, Objective-C, Pascal, Perl, PHP, Python, Ruby, Tcl, Velocity, Windows PowerShell, XSL/XSLT
  • IF NOT (ActionScript 3.0) video

de:Bedingte Anweisung es:Sentencia condicional et:Tingimuslause ko:조건문 hr:Uvjetna naredba he:פקודת if hu:Feltételes utasítás ja:If文 pl:Instrukcja warunkowa pt:Estrutura de seleção ru:Условная инструкция uk:Умовний перехід