![IF-THEN-ELSE-END flowchart](https://upload.wikimedia.org/wikipedia/commons/4/4d/IF-THEN-ELSE-END_flowchart.svg)
In
computer science
Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, conditionals (that is, conditional statements, conditional expressions and conditional constructs,) are
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined
boolean ''condition'' evaluates to true or false. In terms of
control flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
, the decision is always achieved by selectively altering the control flow based on some condition (apart from the case of
branch predication
In computer science, predication is an architectural feature that provides an alternative to conditional transfer of control, as implemented by conditional branch machine instructions. Predication works by having conditional (''predicated'') non- ...
).
Although
dynamic dispatch
In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
is not usually classified as a conditional construct, it is another way to select between alternatives at
runtime.
Terminology
In
imperative programming
In computer science, imperative programming is a programming paradigm of software that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program c ...
languages, the term "conditional
statement" is usually used, whereas in
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
, the terms "conditional
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
" or "conditional construct" are preferred, because these terms all have distinct meanings.
If–then(–else)
The
if–then
construct (sometimes called
if–then–else
) is common across many programming languages. Although the syntax varies from language to language, the basic structure (in
pseudocode
In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
form) looks like this:
If (boolean condition) Then
(consequent)
Else
(alternative)
End If
For example:
If stock=0 Then
message= order new stock
Else
message= there is stock
End If
In the example code above, the part represented by ''(boolean condition)'' constitutes a conditional ''expression'', having intrinsic value (e.g., it may be substituted by either of the values
True
or
False
) but having no intrinsic meaning. In contrast, the combination of this expression, the
If
and
Then
surrounding it, and the consequent that follows afterward constitute a conditional ''statement'', having intrinsic meaning (e.g., expressing a coherent logical rule) but no intrinsic value.
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
Block or blocked may refer to:
Arts, entertainment and media Broadcasting
* Block programming, the result of a programming strategy in broadcasting
* W242BX, a radio station licensed to Greenville, South Carolina, United States known as ''96.3 ...
(which is usually optional), or if there is no
else
branch, then after the
end If
.
After either branch has been executed,
control
Control may refer to:
Basic meanings Economics and business
* Control (management), an element of management
* Control, an element of management accounting
* Comptroller (or controller), a senior financial officer in an organization
* Controllin ...
returns to the point after the
end If
.
History and development
In early programming languages, especially some dialects of
BASIC
BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
in the 1980s
home computers, an
if–then
statement could only contain
GOTO
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
statements (equivalent to a
branch
A branch, sometimes called a ramus in botany, is a woody structural member connected to the central trunk (botany), trunk of a tree (or sometimes a shrub). Large branches are known as boughs and small branches are known as twigs. The term '' ...
instruction). This led to a hard-to-read style of programming known as
spaghetti programming
Spaghetti code is a pejorative phrase for unstructured and difficult-to-Software maintenance, maintain source code. Spaghetti code can be caused by several factors, such as volatile Software project management, project requirements, lack of program ...
, with programs in this style called ''spaghetti code''. As a result,
structured programming
Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
, 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
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
family of languages, and ALGOL-like languages such as
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
and
Modula-2
Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It w ...
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, 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 such as
C,
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
,
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
and
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (cl ...
.
The "dangling else" problem
The
else
keyword is made to target a specific
if–then
statement preceding it, but for
nested
''Nested'' is the seventh studio album by Bronx-born singer, songwriter and pianist Laura Nyro, released in 1978 on Columbia Records.
Following on from her extensive tour to promote 1976's ''Smile'', which resulted in the 1977 live album ''Season ...
if–then
statements, classic programming languages such as
ALGOL 60
ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
struggled to define which specific statement to target. Without clear boundaries for which statement is which, an
else
keyword could target any preceding
if–then
statement in the nest, as parsed.
if a then if b then s else s2
can be parsed as
if a then (if b then s) else s2
or
if a then (if b then s else s2)
depending on whether the
else
is associated with the first
if
or second
if
. This is known as the
dangling else
The dangling else is a problem in programming of parser generators in which an optional else clause in an if–then(–else) statement results in nested conditionals being ambiguous. Formally, the reference context-free grammar of the language i ...
problem, and is resolved in various ways, depending on the language (commonly via the
end if
statement or
brackets).
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.
if condition then
''-- statements''
elseif condition then
''-- more statements''
elseif condition then
''-- more statements;''
...
else
''-- other statements;''
end if;
For example, for a shop offering as much as a 30% discount for an item:
if discount < 11% then
print (you have to pay $30)
elseif discount<21% then
print (you have to pay $20)
elseif discount<31% then
print (you have to pay $10)
end if;
In the example above, if the discount is 10%, then the first if statement will be evaluated as true and "you have to pay $30" will be printed out. All other statements below that first if statement will be skipped.
The
elseif
statement, in the
Ada
Ada may refer to:
Places
Africa
* Ada Foah, a town in Ghana
* Ada (Ghana parliament constituency)
* Ada, Osun, a town in Nigeria
Asia
* Ada, Urmia, a village in West Azerbaijan Province, Iran
* Ada, Karaman, a village in Karaman Province, Tur ...
language for example, is simply
syntactic sugar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
for
else
followed by
if
. In Ada, the difference is that only one
end if
is needed, if one uses
elseif
instead of
else
followed by
if
.
PHP
PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
uses the
elseif
keyword
PHP elseif syntax
' both for its curly brackets or colon syntaxes.
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
provides the keyword
elsif
to avoid the large number of braces that would be required by multiple
if
and
else
statements.
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
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. Some implementations of
BASIC
BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
, such as
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (cl ...
,
Visual Basic ElseIf syntax
' use
ElseIf
too. Similarly, the earlier UNIX shells (later gathered up to the POSIX shell syntax
') use elif 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
Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of ALGOL 6 ...
,
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
,
BCPL
BCPL ("Basic Combined Programming Language") is a procedural, imperative, and structured programming language. Originally intended for writing compilers for other languages, BCPL is no longer in common use. However, its influence is still ...
and
C, this special syntax for the
else if
construct is not present, nor is it present in the many syntactical derivatives of C, such as
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
,
ECMAScript
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scripting o ...
, 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.
This design choice has a slight "cost". Each
else if
branch effectively adds an extra nesting level. This complicates the job for the compiler (or the people who write the compiler), because the compiler must analyse and implement arbitrarily long
else if
chains recursively.
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 the
switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function some ...
, also called case-statement or select-statement. Conversely, in languages that do not have a switch statement, these can be produced by a sequence of
else if
statements.
If–then–else 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 may not be permitted in the context of a value).
Algol family
ALGOL 60
ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
and some other members of the
ALGOL
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
family allow
if–then–else
as an expression:
myvariable := if x > 20 then 1 else 2
Lisp dialects
In dialects of
Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
–
Scheme A scheme is a systematic plan for the implementation of a certain idea.
Scheme or schemer may refer to:
Arts and entertainment
* ''The Scheme'' (TV series), a BBC Scotland documentary series
* The Scheme (band), an English pop band
* ''The Schem ...
,
Racket and
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
– the first of which was inspired to a great extent by ALGOL:
;; Scheme
(define myvariable (if (> x 12) 1 2)) ; Assigns 'myvariable' to 1 or 2, depending on the value of 'x'
;; Common Lisp
(let ((x 10))
(setq myvariable (if (> x 12) 2 4))) ; Assigns 'myvariable' to 2
Haskell
In
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
98, there is only an ''if expression'', no ''if statement'', and the
else
part is compulsory, as every expression must have some value.
Haskell 98 Language and Libraries: The Revised Report
' Logic that would be expressed with conditionals in other languages is usually expressed with
pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
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:
[If-then-else Proposal on HaskellWiki]
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
C-like languages
C and C-like languages have a special
ternary operator
In mathematics, a ternary operation is an ''n''- ary operation with ''n'' = 3. A ternary operation on a set ''A'' takes any given three elements of ''A'' and combines them to form a single element of ''A''.
In computer science, a ternary operator ...
(
?:) for conditional expressions with a function that may be described by a template like this:
condition ? evaluated-when-true : evaluated-when-false
This means that it can be inlined into expressions, unlike if-statements, in C-like languages:
my_variable = x > 10 ? "foo" : "bar"; // In C-like languages
which can be compared to the Algol-family if–then–else ''expressions'' (in contrast to a ''statement'') (and similar in Ruby and Scala, among others).
To accomplish the same using an if-statement, this would take more than one line of code (under typical layout conventions), and require mentioning "my_variable" twice:
if (x > 10)
my_variable = "foo";
else
my_variable = "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, while others argue that concise expressions are easier to read than statements spread over several lines containing repetition.
Small Basic
Microsoft Small Basic is a programming language, interpreter and associated IDE. Microsoft's simplified variant of BASIC, it is designed to help students who have learnt visual programming languages such as Scratch learn text-based programming ...
x = TextWindow.ReadNumber()
If (x > 10) Then
TextWindow.WriteLine("My variable is named 'foo'.")
Else
TextWindow.WriteLine("My variable is named 'bar'.")
EndIf
First, when the user runs the program, a cursor appears waiting for the reader to type a number. If that number is greater than 10, the text "My variable is named 'foo'." is displayed on the screen. If the number is smaller than 10, then the message "My variable is named 'bar'." is printed on the screen.
Visual Basic
In
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (cl ...
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.
Tcl
In
Tcl
TCL or Tcl or TCLs may refer to:
Business
* TCL Technology, a Chinese consumer electronics and appliance company
**TCL Electronics, a subsidiary of TCL Technology
* Texas Collegiate League, a collegiate baseball league
* Trade Centre Limited, a ...
if
is not a keyword but a function (in Tcl known as command or
proc
). For example
if
invokes a function named
if
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 the
if
function receives the condition as a string value and is responsible to evaluate this string as an expression in the callers scope.
Such a behavior is possible by using
uplevel
and
expr
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).
Because
if
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 an empty string if none of the expressions was non-zero and there was no bodyN.
Rust
In
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH ...
,
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 the
if
expression's type is known at compile time, each branch must evaluate to a value of the same type. For this reason, an
else
branch is effectively compulsory unless the other branches evaluate to
()
, because an
if
without an
else
can always evaluate to
()
by default.
// Assign my_variable some value, depending on the value of x
let my_variable = if x > 20 else ;
// This variant will not compile because 1 and () have different types
let my_variable = if x > 20 ;
// Values can be omitted when not needed
if x > 20
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:
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
GOTO label3
Because this
arithmetic IF
The arithmetic IF statement is a three-way arithmetic conditional statement, first seen in the first release of Fortran in 1957, and found in all later versions, and some other programming languages, such as FOCAL. Unlike the logical IF stateme ...
is equivalent to multiple
GOTO
statements that could jump to anywhere, 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
The IBM 704 is a large digital mainframe computer introduced by IBM in 1954. It was the first mass-produced computer with hardware for floating-point arithmetic. The IBM 704 ''Manual of operation'' states:
The type 704 Electronic Data-Pro ...
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.
Object-oriented implementation in Smalltalk
In contrast to other languages, in
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
the conditional statement is not a
language construct
In computer programming, a language construct is a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of the programming language.
The term "language construct" is often used ...
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'
JavaScript
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
uses if-else statements similar to those in
C languages or similar. A boolean value is accepted within parentheses between the reserved ''if'' keyword and a left curly bracket.
if (Math.random() < 0.5) else
The above example takes the conditional of
Math.random() < 0.5
which outputs
true
if a random float value between 0 and 1 is greater than 0.5. The statement uses it to randomly choose between outputting
You got Heads!
or
You got Tails!
to the console. Else and else-if statements can also be chained after the curly bracket of the statement preceding it as many times as necessary, as shown below:
var x = Math.random();
if (x < 1/3) else if (x < 2/3) else
Lambda calculus
In
Lambda calculus
Lambda calculus (also written as ''λ''-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation ...
, the concept of an if-then-else conditional can be expressed using the expressions:
true = λx. λy. x
false = λx. λy. y
ifThenElse = (λc. λx. λy. (c x y))
# true takes up to two arguments and once both are provided (see
currying
In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. For example, currying a function f that ...
), it returns the first argument given.
# false takes up to two arguments and once both are provided(see
currying
In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. For example, currying a function f that ...
), it returns the second argument given.
# ifThenElse 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 ifThenElse 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 ifThenElse is passed two functions as the left and right conditionals; it is necessary to also pass an empty tuple () to the result of ifThenElse in order to actually call the chosen function, otherwise ifThenElse 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, true, false, and ifThenElse 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:
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.
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 True and False being singleton objects that respond to messages ifTrue/ifFalse differently.
Haskell used to use this exact model for its Boolean type, but at the time of writing, most Haskell programs use syntactic sugar "if a then b else c" construct which unlike ifThenElse does not compose unless
either wrapped in another function or re-implemented as shown in The Haskell section of this page.
Case and switch statements
Switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function some ...
s (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
In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power con ...
, such as
lookup table
In computer science, a lookup table (LUT) is an array that replaces runtime computation with a simpler array indexing operation. The process is termed as "direct addressing" and LUTs differ from hash tables in a way that, to retrieve a value v wi ...
s. In dynamic languages, the cases may not be limited to constant expressions, and might extend to
pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
, as in the
shell script
A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manip ...
example on the right, where the '*)' implements the default case as a
regular expression
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or ...
matching any string.
Pattern matching
Pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
may be seen as an alternative to both ''if–then–else'', and ''case'' statements. It is available in many programming languages with functional programming features, such as
Wolfram Language
The Wolfram Language ( ) is a general multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary structures and data. It is ...
,
ML and many others. Here is a simple example written in the
OCaml
OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
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
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
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.
Hash-based conditionals
In programming languages that have
associative array
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an as ...
s or comparable data structures, such as
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
,
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
,
PHP
PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
or
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, it is idiomatic to use them to implement conditional assignment.
pet = input("Enter the type of pet you want to name: ")
known_pets =
my_name = known_pets et
In languages that have
anonymous function
In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to ...
s or that allow a programmer to assign a named function to a variable reference, conditional flow can be implemented by using a hash as a
dispatch table
In computer science, a dispatch table is a table of pointers or memory addresses to functions or methods. Use of such a table is a common technique when implementing late binding in object-oriented programming.
Perl implementation
The followin ...
.
Predication
An alternative to conditional branch instructions is
predication. Predication is an
architectural
Architecture is the art and technique of designing and building, as distinguished from the skills associated with construction. It is both the process and the product of sketching, conceiving, planning, designing, and constructing buildings o ...
feature that enables instructions to be conditionally executed instead of modifying the
control flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
.
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.
See also
*
Branch (computer science)
A branch is an instruction in a computer program that can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order. ''Branch'' (or ''branching'', ''branc ...
*
Conditional compilation
In computer programming, conditional compilation is a compilation technique which results in an executable program that is able to be altered by changing specified parameters. This technique is commonly used when these alterations to the program a ...
*
Dynamic dispatch
In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
for another way to make execution choices
*
McCarthy Formalism for history and historical references
*
Named condition
COBOL (; an acronym for "common business-oriented language") is a Compiled language, compiled English-like computer programming language designed for business use. It is an imperative programming, imperative, procedural programming, procedural ...
*
Relational operator
In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality (''e.g.'', ) and inequalities (''e.g.'', ).
In prog ...
*
Test (Unix)
test is a command-line utility found in Unix, Plan 9, and Unix-like operating systems that evaluates conditional expressions. test was turned into a shell builtin command in 1981 with UNIX System III and at the same time made available under th ...
*
Yoda conditions
In programming jargon, Yoda conditions (also called ''Yoda notation'') is a programming style where the two parts of an expression are reversed from the typical order in a conditional statement. A Yoda condition places the constant portion of th ...
*
Conditional move
In computer science, predication is an architectural feature that provides an alternative to conditional transfer of control, as implemented by conditional branch machine instructions. Predication works by having conditional (''predicated'') non- ...
References
External links
*
IF NOT (ActionScript 3.0)video
{{DEFAULTSORT:Conditional (programming)
Articles with example pseudocode
Articles with example C code
Articles with example Pascal code
Articles with example Haskell code
Articles with example Python (programming language) code