

Incomputer programming, aconditionalstatement directs programcontrol flow based on the value of acondition; aBoolean expression. A conditionalexpression evaluates to a value without theside-effect of changing control flow.
Many programming languages (such asC) have distinct conditional statements and expressions. In purefunctional programming, a conditional expression does not have side-effects, many functional programming languages with conditional expressions (such as Lisp) support side-effects.
Although the syntax of an if-then-else statement varies by language, the general syntax is shown aspseudocode below. The part represented by thecondition placeholder is an expression that evaluates to either true or false. If true, control passes toconsequent and when complete to afterend if. If false, control passes toalternative and when complete to afterend if. As the else clause is optional, theelsealternative part can be omitted. Typically, bothconsequent andalternative can be either a single statement or ablock of statements.
ifconditionthenconsequentelsealternativeendif
The following example, also in pseudocode, replaces placeholders with example logic.
ifstock=0thenmessage='order new stock'elsemessage='there is stock'endif
In early programming languages, especially dialects ofBASIC, an if–then-else statement could only containgoto statements but this tended to result in hard-to-readspaghetti 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 theALGOL family of languages, includingPascal andModula-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 asC,Java,JavaScript andVisual Basic.
The convention is that anelse clause, like thethen clause, responds to the nearest precedingif clause; however, the semantics in some early languages, such asALGOL 60, ofnested conditionals, were less than clear; that is to say, the syntax was inadequate to specify one-and-always-the-same predicateif clause. Thus, the parser might randomly pair theelse with any one of the perhaps manifoldif clauses in the intended nested hierarchy.
ifAthenifBthenSelseS2
ifAthenifBthenSelseS2
ifAthen(ifBthenS)elseS2end
ifAthen(ifBthenS)elseS2end
ifAthen(ifBthenSelseS2)
ifAthen(ifBthenSelseS2)end
This is known as thedangling else problem. It is resolved in various ways, depending on the language (in some, by means of explicit block-ending syntax (such asend if ) or a block enclosure, such as curly brackets ({⋯} ).
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:
ifcondition1thenblock1elseifcondition2thenblock2elseifcondition3thenblock3...elseblock4endif
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 "you have to pay $30" is printed. All other statements below that first if statement are skipped.
ifdiscount<11%thenprint"You have to pay $30."elseifdiscount<21%thenprint"You have to pay $20."elseifdiscount<31%thenprint"You have to pay $10."endif
Only oneend if is needed if one useselse if instead ofelse followed byif.
InALGOL 68, the 1968 “Draft Report” (circulated as a supplement toALGOL Bulletin no. 26) still used thebold keywordelsf in “contracted” conditionals.[1]The spellingelif was then standardized in the “Revised Report on the Algorithmic Language ALGOL 68” (1973), which lists both thebold wordsif ~then ~elif ~else ~fi and their “brief” symbols, whereelif corresponds to|: in the compact form( ~ | ~ |: ~ | ~ | ~ ).[2]
InAda, theelseif keyword issyntactic sugar for the two wordselseif.PHP also supports anelseif keyword[3] both for its curly brackets or colon syntaxes.Perl andRuby provide the keywordelsif to avoid the large number of braces that would be required by multipleif andelse statements.Python uses the special keywordelif because structure is denoted by indentation rather than braces, so a repeated use ofelse andif would require increased indentation after every condition.Visual Basic, supportsElseIf.[4] Similarly, the earlierUNIX shells (later gathered up to the POSIX shell syntax[5]) useelif too, but giving the choice of delimiting with spaces, line breaks, or both.
However, in many languages more directly descended from Algol, such asSimula,Pascal, BCPL andC, this special syntax for theelse if construct is not present, nor is it present in the many syntactical derivatives of C, such asJava,ECMAScript, and so on. This works because in these languages, anysingle statement (in this caseif cond...) can follow a conditional without being enclosed in a block.[clarification needed]
If all terms in the sequence of conditionals are testing the value of a single expression (e.g.,if x = 0, else if x = 1, else if x = 2 ...), an alternative is theswitch statement. In a language that does not have a switch statement, these can be encoded as a chained if-then-else.
Aswitch 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. Anoptimizing compiler may use acontrol 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 topattern matching, as in theshell script example on the right, where the '*)' implements the default case as aregular expression matching any string.
TheGuarded Command Language (GCL) ofEdsger Dijkstra supports conditional execution as a list of commands consisting of a Boolean-valuedguard (corresponding to acondition) 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 → Snfi
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 inConcurrent Pascal andoccam.
The earliest conditional statement in Fortran, up toFortran 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.[6]
In the following code, control passes to one of the labels based on the value ofe.
IF(e)label1,label2,label3
This is equivalent to the following sequence.
e_temp=eIF(e_temp.LT.0)GOTOlabel1IF(e_temp.EQ.0)GOTOlabel2IF(e_temp.GT.0)GOTOlabel3
As it acts likegoto, arithmetic if is unstructured; notstructured programming. It was the only conditional statement in the original implementation of Fortran on theIBM 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 evaluatedonce 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 contrast to other languages, inSmalltalk the conditional statement is not alanguage construct but defined in the classBoolean as an abstract method that takes two parameters, bothclosures.Boolean has two subclasses,True andFalse, which both define the method,True executing the first closure only,False executing the second closure only.[7]
var=conditionifTrue: ['foo' ]ifFalse: ['bar' ]
JavaScript supports if-else statements similar toC syntax. The following example has conditionalMath.random()<0.5 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 outputtingYou got Heads! orYou got Tails!.
if(Math.random()<0.5){console.log("You got Heads!");}else{console.log("You got Tails!");}
Conditionals can be chained as shown below:
varx=Math.random();if(x<1/3){console.log("One person won!");}elseif(x<2/3){console.log("Two people won!");}else{console.log("It's a three-way tie!");}
InLambda calculus, the concept of an if-then-else conditional can be expressed using the following expressions:
true = λx. λy. xfalse = λx. λy. yifThenElse = (λc. λx. λy. (c x y))
Note: ififThenElse is passed two functions as the left and right conditionals; it isnecessary to also pass an empty tuple() to the result ofifThenElse in order to actually call the chosen function, otherwiseifThenElse will just return thefunction 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.(ifThenElsetrue23))(λx.λy.x)(λx.λy.y)(λc.λl.λr.clr))
Here,true, false, andifThenElse 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:
varcomputationResult=((_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:
varcomputationResult=((_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.(ifThenElsetrue(λFirstBranch.FirstBranch)(λSecondBranch.SecondBranch)))(λx.λy.x)(λx.λy.y)(λc.λl.λr.clr))((λtrue.λfalse.λifThenElse.(ifThenElsefalse(λFirstBranch.FirstBranch)(λSecondBranch.SecondBranch)))(λx.λy.x)(λx.λy.y)(λc.λl.λr.clr))
Smalltalk uses a similar idea for its true and false representations, withTrue andFalse being singleton objects that respond to messagesifTrue/ifFalse differently.
Haskell used to use this exact model for its Boolean type, but at the time of writing, most Haskell programs use syntactic sugarifathenbelsec construct which unlikeifThenElse does not compose unlesseither wrapped in another function or re-implemented as shown in The Haskell section of this page.
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 byJohn McCarthy during his research into symbolic processing and LISP in the late 1950s.
ALGOL 60 and some other members of theALGOL family allowif–then–else as an expression. The idea of including conditional expressions was suggested by John McCarthy, though the ALGOL committee decided to use English words rather than McCarthy's mathematical syntax:
myvariable:=ifx>20then1else2
Compound statements are all terminated (guarded) by distinctive closing brackets:
IF conditionTHEN statements [ELSE statements ]FI "brief" form: ( condition | statements | statements )
IF condition1THEN statementsELIF condition2THEN statements [ELSE statements ]FI "brief" form: ( condition1 | statements |: condition2 | statements | statements )
This scheme not only avoids thedangling else problem but also avoids having to useBEGIN andEND in embeddedstatement sequences.
CASE switchIN statements, statements,... [OUT statements ]ESAC "brief" form: ( switch | statements,statements,... | statements )
CASE switch1IN statements, statements,...OUSE switch2IN statements, statements,... [OUT statements ]ESAC "brief" form ofCASE statement: ( switch1 | statements,statements,... |: switch2 | statements,statements,... | statements )
Choice clause example withBrief symbols:
PROC days in month = (INT year, month)INT: (month| 31, (year÷×4=0 ∧ year÷×100≠0 ∨ year÷×400=0 | 29 | 28 ), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
Conditional expressions have always been a fundamental part ofLisp . In pure LISP, theCOND function is used. In dialects such asScheme,Racket andCommon Lisp :
;; Scheme(define(myvariablex)(if(>x12)12)); Assigns 'myvariable' to 1 or 2, depending on the value of 'x'
;; Common Lisp(let((x10))(setqmyvariable(if(>x12)24))); Assigns 'myvariable' to 2
InHaskell 98, there is only anif expression, noif statement, and theelse part is compulsory, as every expression must have some value.[8] Logic that would be expressed with conditionals in other languages is usually expressed withpattern matching in recursive functions.
Because Haskell islazy, it is possible to write control structures, such asif, as ordinary expressions; the lazy evaluation means that anif function can evaluate only the condition and proper branch (where a strict language would evaluate all three). It can be written like this:[9]
if'::Bool->a->a->aif'Truex_=xif'False_y=y
C and related languages support aternary operator that provides for conditional expressions like:
condition ?true-value :false-value
Ifcondition is true, then the expression evaluates totrue-value; otherwise tofalse-value. In the following code, r is assigned to "foo" if x > 10; otherwise to "bar".
r=x>10?"foo":"bar";
To accomplish the same using an if-statement, this would take more than one statement, and require mentioningr twice:
if(x>10)r="foo";elser="bar";
Some argue that the explicit if-then statement is easier to read and that it may compile to more efficient code than the ternary operator,[10] while others argue that concise expressions are easier to read and better since they have less repeated clauses.
InVisual Basic and some other languages, a function calledIIf 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.
InTclif is not a keyword but a function (in Tcl known as command orproc). For example
if{$x>10}{puts"Foo!"}
invokes a function namedif passing 2 arguments: The first one being the condition and the second one being the true branch. Both arguments are passed as strings (in Tcl everything within curly brackets is a string).
In the above example the condition is not evaluated before calling the function. Instead, the implementation of theif function receives the condition as a string value and is responsible to evaluate this string as an expression in the callers scope.[11]
Such a behavior is possible by usinguplevel andexpr commands. Uplevel makes it possible to implement new control constructs as Tcl procedures (for example, uplevel could be used to implement the while construct as a Tcl procedure).[12]
Becauseif is actually a function it also returns a value. The return value from the command is the result of the body script that was executed, or anempty string if none of the expressions was non-zero and there was no bodyN.[13]
InRust,if is always an expression. It evaluates to the value of whichever branch is executed, or to the unit type() if no branch is executed. If a branch does not provide a return value, it evaluates to() by default. To ensure theif expression's type is known atcompile time, each branch must evaluate to a value of the same type. For this reason, anelse branch is effectively compulsory unless the other branches evaluate to(), because anif without anelse can always evaluate to() by default.[14]
The following assignsr to 1 or 2 depending on the value of x.
letr=ifx>20{1}else{2};
Values can be omitted when not needed.
ifx>20{println!("x is greater than 20");}
Pattern matching is an alternative to conditional statements (such as if–then–else and switch). It is available in many languages with functional programming features, such asWolfram Language,ML and many others. Here is a simple example written in theOCaml language:
matchfruitwith|"apple"->cookpie|"coconut"->cookdango_mochi|"banana"->mix;;
The power of pattern matching is the ability toconcisely match not only actions but alsovalues to patterns of data. Here is an example written inHaskell which illustrates both of these features:
map_[]=[]mapf(h:t)=fh:mapft
This code defines a functionmap, 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 speakingalways 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.
In programming languages that haveassociative arrays or comparable data structures, such asPython,Perl,PHP orObjective-C, it is idiomatic to use them to implement conditional assignment.[15]
pet=input("Enter the type of pet you want to name: ")known_pets={"Dog":"Fido","Cat":"Meowsles","Bird":"Tweety",}my_name=known_pets[pet]
In languages that haveanonymous functions or that allow a programmer to assign a named function to a variable reference, conditional flow can be implemented by using a hash as adispatch table.
An alternative to conditional branch instructions isbranch predication. Predication is anarchitectural feature that enables instructions to be conditionally executed instead of modifying thecontrol flow.
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 | Conditional expressions | Arithmetic if | Pattern matching[A] | ||
|---|---|---|---|---|---|---|---|
| then | else | else–if | |||||
| Ada | Yes | Yes | Yes | Yes | Yes | No | No |
| ALGOL-60 | Yes | Yes | Unneeded[C] | No | Yes | No | No |
| ALGOL 68 | Yes | Yes | Yes | Yes | Yes | Yes -case clause | Yes - Conformity clause |
| APL | No | Yes | Yes | Yes | Yes | No | No |
| Bash shell | Yes | Yes | Yes | Yes | Yes | No | Yes |
| C,C++ | No | Yes | Unneeded[B][C] | Fall-through | Yes | No | No |
| C# | No | Yes | Unneeded[B][C] | Yes | Yes | No | No |
| COBOL | Unneeded | Yes | Unneeded[C] | Yes | No | No | No |
| Eiffel | Yes | Yes | Yes | Yes | Yes | No | No |
| F# | Yes | Yes | Yes | Yes[D] | Yes | No | Yes |
| Fortran | Yes | Yes | Yes | Yes | Yes[G] | Yes[I] | No |
| Go | No | Yes | Unneeded[C] | Yes | No | No | No |
| Haskell | Yes | Needed | Unneeded[C] | Yes[D] | Yes | No | Yes |
| Java | No | Yes | Unneeded[C] | Fall-through[16] | Yes | No | No |
| ECMAScript (JavaScript) | No | Yes | Unneeded[C] | Fall-through[17] | Yes | No | No |
| Mathematica | No | Yes | Yes | Yes | Yes | No | Yes |
| Oberon | Yes | Yes | Yes | Yes | No | No | No |
| Perl | No | Yes | Yes | Yes | Yes | No | No |
| PHP | No | Yes | Yes | Fall-through | Yes | No | Yes |
| Pascal,Object Pascal (Delphi) | Yes | Yes | Unneeded | Yes | No | No | No |
| Python | No | Yes | Yes | Yes | Yes | No | Yes |
| QuickBASIC | Yes | Yes | Yes | Yes | No | No | No |
| Ruby | Yes | Yes | Yes | Yes | Yes | No | Yes[H] |
| Rust | No | Yes | Yes | Yes[D] | Yes | No | Yes |
| Scala | No | Yes | Unneeded[C] | Fall-through[citation needed] | Yes | No | Yes |
| SQL | Yes[F] | Yes | Yes | Yes[F] | Yes | No | No |
| Swift | No | Yes | Yes | Yes | Yes | No | Yes |
| Tcl | No | Yes | Yes | Yes | Yes | No | Yes |
| Visual Basic, classic | Yes | Yes | Yes | Yes | Yes | No | No |
| Visual Basic .NET | Yes | Yes | Yes | Yes | Yes | No | No |
| Windows PowerShell | No | Yes | Yes | Fall-through | Yes | No | No |
else if in the C family of languages, and in COBOL and Haskell, is not a language feature but a set of nested and independentif 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.case construct,regular expression matching is among the conditional flow-control alternatives available. For an example, seethis Stack Overflow question.CASE" expressionCASEWHENcond1THENexpr1WHENcond2THENexpr2[...]ELSEexprDfltEND works likeif ... else if ... else, whereas a "simpleCASE" expression:CASEexprWHENval1THENexpr1[...]ELSEexprDfltEND works like a switch statement. For details and examples seeCase (SQL).MERGE intrinsic. Fortran 2023 added the C-like ternary operator.if was marked as obsolescent in Fortran 90. It was deleted as of the Fortran 2018 Standard.symbol tables: "boldelse if" → "elif"; "briefelse if" → "|:")