Conditional (computer programming)
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 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 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, theelse 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 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” still used the bold keyword ' in “contracted” conditionals.
The spelling ' was then standardized in the “Revised Report on the Algorithmic Language ALGOL 68”, 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 keyword 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.
Similarly, the earlier UNIX shells 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 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, 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 of Edsger Dijkstra supports conditional execution as a list of commands consisting of a Boolean-valued guard and its corresponding statement. In GCL, exactly one of the statements whose guards is true is evaluated, but which one is arbitrary. In this codeif 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 is <0, 0, or >0.In the following code, control passes to one of the labels based on the value of.
IF label1, label2, label3
This is equivalent to the following sequence.
e_temp = e
IF GOTO label1
IF GOTO label2
IF 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 classBoolean 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:
ifFalse:
In JavaScript
JavaScript supports if-else statements similar to C syntax. The following example has conditional which is true if the random float is greater than 0.5. The statement uses it to randomly choose between outputting or.if else
Conditionals can be chained as shown below:
var x = Math.random;
if else if else
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 =
- takes up to two arguments and once both are provided, it returns the first argument given.
- takes up to two arguments and once both are provided, 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. 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.
In a system where numbers can be used without definition, the above can be expressed as a single closure below:
)
Here, and are bound to their respective definitions which are passed to their scope at the end of their block.
A working JavaScript analogy to this is as follows:
var computationResult =
)));
The code above with multivariable functions looks like this:
var computationResult = =>
_ifThenElse
) => x, => y, => c);
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.
)
))
)
))
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
Algol
ALGOL 60 and some other members of the ALGOL 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 := if x > 20 then 1 else 2
[ALGOL 68]
Compound statements are all terminated by distinctive closing brackets:- IF choice clauses:
"brief" form:
IF condition1 THEN statements ELIF condition2 THEN statements FI
"brief" form:
This scheme not only avoids the dangling else problem but also avoids having to use
BEGIN and END in embedded statement sequences.- CASE choice clauses:
"brief" form:
CASE switch1 IN statements, statements,... OUSE switch2 IN statements, statements,... ESAC
"brief" form of CASE statement:
Choice clause example with Brief symbols:
PROC days in month = INT:
;
Lisp
Conditional expressions have always been a fundamental part of Lisp. In pure LISP, theCOND function is used. In dialects such as Scheme, Racket and Common Lisp:;; Scheme
; Assigns 'myvariable' to 1 or 2, depending on the value of 'x'
;; Common Lisp
)
) ; Assigns 'myvariable' to 2
Haskell
In Haskell 98, there is only an if expression, no if statement, and theelse part is compulsory, as every expression must have some value. 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. It can be written like this:
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
C-like languages
C and related languages support a ternary operator that provides for conditional expressions like:condition ? true-value : false-value
If condition is true, then the expression evaluates to true-value; otherwise to false-value. In the following code, r is assigned to "foo" if x > 10, and to "bar" if not.
r = x > 10 ? "foo" : "bar";
To accomplish the same using an if-statement, this would take more than one statement, and require mentioning twice:
if
r = "foo";
else
r = "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 and better since they have less repeated clauses.
Visual Basic
In Visual 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.Tcl
In Tclif is not a keyword but a function. For exampleif
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 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.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,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.The following assigns to 1 or 2 depending on the value of x.
let r = if x > 20 else ;
Values can be omitted when not needed.
if x > 20
Pattern matching
Pattern matching is an alternative to conditional statements. It is available in many languages with functional programming features, such as Wolfram Language, ML and many others. Here is a simple example written in the OCaml language:match fruit with
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 = f h : map f t
This code defines a function map, which applies the first argument to each of the elements of the second argument, 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 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 arrays or comparable data structures, such as Python, Perl, PHP or Objective-C, it is idiomatic to use them to implement conditional assignment.pet = input
known_pets =
my_name = known_pets
In languages that have anonymous 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 a dispatch table.