In computer programming, a conditional statement directs program control flow based on the value of a condition; a Boolean expression. A conditional expression evaluates to a value without the side-effect of changing control flow.
Many programming languages (such as C) have distinct conditional statements and expressions. In pure functional programming, a conditional expression does not have side-effects, many functional programming languages with conditional expressions (such as Lisp) support side-effects.
Conditional statement
If-then-else statement
Although the syntax of an if-then-else statement varies by language, the general syntax is shown as pseudocode below. The part represented by the condition placeholder is an expression that evaluates to either true or false. If true, control passes to consequent and when complete to after . If false, control passes to alternative and when complete to after . As the else clause is optional, the else alternative part can be omitted. Typically, both consequent and alternative can be either a single statement or a block of statements.
if condition then consequent else alternative end if
The following example, also in pseudocode, replaces placeholders with example logic.
if stock = 0 then message = 'order new stock' else message = 'there is stock' end if
History and development In early programming languages, especially dialects of BASIC, an if–then-else statement could only contain goto statements but this tended to result in hard-to-read spaghetti code. As a result, structured programming, which supports control flow via code blocks, gained in popularity, until it became the norm in most BASIC variants and all languages. Such mechanisms and principles were based on the ALGOL family of languages, including Pascal and Modula-2. While it is possible to use goto in a structured way, structured programming makes this easier. A structured if–then–else statement is one of the key elements of structured programming, and it is present in most popular languages such as C, Java, JavaScript and Visual Basic.
Dangling else
The convention is that an clause, like the clause, responds to the nearest preceding clause. However, the semantics of nested conditionals in some early languages such as ALGOL 60 were less than clear; the syntax was inadequate to always specify the same predicate clause. Thus, the parser might randomly pair the with any one of the perhaps manifold clauses in the intended nested hierarchy.
may be parsed either as meaning:
or as meaning:
This is known as the dangling else problem. It is resolved in various ways, depending on the language (in some, by means of explicit block-ending syntax (such as ) or a block enclosure, such as curly brackets ( {⋯} ).
Chaining Chaining conditionals is often provided in a language via an else-if construct. Only the statements following the first condition that is true are executed. Other statements are skipped. In placeholder pseudocode:
if condition1 then block1 else if condition2 then block2 else if condition3 then block3 ... else block4 end if
In the following pseudocode, a shop offers as much as a 30% discount for an item. If the discount is 10%, then the first if statement is true and "" is printed. All other statements below that first if statement are skipped.
if discount < 11% then print "You have to pay $30." else if discount < 21% then print "You have to pay $20." else if discount < 31% then print "You have to pay $10." end if
Only one is needed if one uses instead of followed by .
In ALGOL 68, the 1968 “Draft Report” (circulated as a supplement to ALGOL Bulletin no. 26) still used the bold keyword in “contracted” conditionals. The spelling was then standardized in the “Revised Report on the Algorithmic Language ALGOL 68” (1973), which lists both the words and their “brief” symbols, where corresponds to |: in the compact form ( ~ | ~ |: ~ | ~ | ~ ).
In Ada, the keyword is syntactic sugar for the two words . PHP also supports an keywordPHP elseif syntax both for its curly brackets or colon syntaxes. Perl and Ruby provide the keyword to avoid the large number of braces that would be required by multiple and statements. Python uses the special keyword because structure is denoted by indentation rather than braces, so a repeated use of and would require increased indentation after every condition. Visual Basic, supports .Visual Basic syntax Similarly, the earlier UNIX shells (later gathered up to the POSIX shell syntax) use too, but giving the choice of delimiting with spaces, line breaks, or both.
However, in many languages more directly descended from Algol, such as Simula, Pascal, BCPL and C, this special syntax for the construct is not present, nor is it present in the many syntactical derivatives of C, such as Java, ECMAScript, and so on. This works because in these languages, any single statement (in this case if cond...) can follow a conditional without being enclosed in a block.
If all terms in the sequence of conditionals are testing the value of a single expression (e.g., ...), an alternative is the switch statement. In a language that does not have a switch statement, these can be encoded as a chained if-then-else.
Switch statement A switch statement supports multiway branching, often comparing the value of an expression with constant values and transferring control to the code of the first match. There is usually a provision for a default action if no match is found. An optimizing compiler may use a control table to implement the logic of a switch statement. In a dynamic language, 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.
Guarded conditional The Guarded Command Language (GCL) of Edsger Dijkstra supports conditional execution as a list of commands consisting of a Boolean-valued guard (corresponding to a condition) and its corresponding statement. In GCL, exactly one of the statements whose guards is true is evaluated, but which one is arbitrary. In this code if G0 → S0 □ G1 → S1 ... □ Gn → Sn fi the Gi's are the guards and the Si's are the statements. If none of the guards is true, the program's behavior is undefined.
GCL is intended primarily for reasoning about programs, but similar notations have been implemented in Concurrent Pascal and occam.
Arithmetic if The earliest conditional statement in Fortran, up to Fortran 77, was the arithmetic if statement which jumped to one of three labels depending on whether a value (of type integer, real, or double precision) is <0, 0, or >0.
In the following code, control passes to one of the labels based on the value of .
IF (e) label1, label2, label3
This is equivalent to the following sequence.
e_temp = e IF (e_temp .LT. 0) GOTO label1 IF (e_temp .EQ. 0) GOTO label2 GOTO label3
As it acts like goto, arithmetic if is unstructured, not structured, programming. It was the only conditional statement in the original implementation of Fortran on the IBM 704 computer. On that computer, the test-and-branch op-code had three addresses for those three states. Other computers would have "flag" registers such as positive, zero, negative, even, overflow, carry, associated with the last arithmetic operations and would use instructions such as 'Branch if accumulator negative' then 'Branch if accumulator zero' or similar. Note that the expression is evaluated once only, and in cases such as integer arithmetic where overflow may occur, the overflow or carry flags would be considered also.
The Arithmetic IF statement was listed as obsolescent starting with the Fortran 90 Standard. It was deleted from the Fortran 2018 Standard. Nonetheless, most compilers continue to support it for compatibility with legacy codes.
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.
var = condition ifTrue: [ 'foo' ] ifFalse: [ 'bar' ]
In JavaScript JavaScript supports if-else statements similar to C syntax. The following example has conditional which is true if the random float (value between 0 and 1) is greater than 0.5. The statement uses it to randomly choose between outputting or .
if (Math.random() < 0.5) { console.log("You got Heads!"); } else { console.log("You got Tails!"); }
Conditionals can be chained as shown below:
var x = Math.random(); if (x < 1/3) { console.log("One person won!"); } else if (x < 2/3) { console.log("Two people won!"); } else { console.log("It's a three-way tie!"); }
Lambda calculus In Lambda calculus, the concept of an if-then-else conditional can be expressed using the following expressions: true = λx. λy. x false = λx. λy. y ifThenElse = (λc. λx. λy. (c x y)) takes up to two arguments and once both are provided (see currying), it returns the first argument given. takes up to two arguments and once both are provided(see currying), it returns the second argument given. takes up to three arguments and once all are provided, it passes both second and third argument to the first argument(which is a function that given two arguments, and produces a result). We expect to only take true or false as an argument, both of which project the given two arguments to their preferred single argument, which is then returned. Note: if is passed two functions as the left and right conditionals; it is necessary to also pass an empty tuple to the result of in order to actually call the chosen function, otherwise will just return the function object without getting called.
In a system where numbers can be used without definition (like Lisp, Traditional paper math, so on), the above can be expressed as a single closure below: ((λtrue. λfalse. λifThenElse. (ifThenElse true 2 3) )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r)) Here, and are bound to their respective definitions which are passed to their scope at the end of their block.
A working JavaScript analogy(using only functions of single variable for rigor) to this is as follows: var computationResult = ((_true => _false => _ifThenElse => _ifThenElse(_true)(2)(3) )(x => y => x)(x => y => y)(c => x => y => c(x)(y))); The code above with multivariable functions looks like this: var computationResult = ((_true, _false, _ifThenElse) => _ifThenElse(_true, 2, 3) )((x, y) => x, (x, y) => y, (c, x, y) => c(x, y)); Another version of the earlier example without a system where numbers are assumed is below.
The first example shows the first branch being taken, while second example shows the second branch being taken. ((λtrue. λfalse. λifThenElse. (ifThenElse true (λFirstBranch. FirstBranch) (λSecondBranch. SecondBranch)) )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r))
((λtrue. λfalse. λifThenElse. (ifThenElse false (λFirstBranch. FirstBranch) (λSecondBranch. SecondBranch)) )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r)) Smalltalk uses a similar idea for its true and false representations, with and being singleton objects that respond to messages differently.
Haskell used to use this exact model for its Boolean type, but at the time of writing, most Haskell programs use syntactic sugar construct which unlike does not compose unless either wrapped in another function or re-implemented as shown in The Haskell section of this page.
Conditional expression
Many languages support a conditional expression, which unlike a statement evaluates to a value instead of controlling control flow. The concept of conditional expression was first developed by John McCarthy during his research into symbolic processing and LISP in the late 1950s.
Examples