Ternary conditional operator
In computer programming, the ternary conditional operator is a ternary operator that evaluates to one of two values based on a Boolean expression. The operator is also known as conditional operator, ternary if, immediate if, or inline if. Although many ternary operators are theoretically possible, the conditional operator is commonly used and other ternary operators rare, so the conditional variant is commonly referred to as the ternary operator.
Typical syntax for an expression using the operator is like or. One can read it aloud as "if a then b otherwise c". The form is the most common, but alternative syntax exists. For example, Raku uses the syntax to avoid confusion with the infix operators and, whereas in Visual Basic, it takes the form.
The construct first appeared in CPL, in which equivalent syntax for is
a → b, c.Patterns
Assignment
The value of the operator can be assigned to a variable. For a weakly typed language, the data type of the selected value may determine the type of the assigned value. For a strongly typed language, both value expressions must evaluate to a type that is compatible with the target variable.The operator is similar to the way conditional expressions work in functional programming languages, like Scheme, ML, Haskell, and XQuery, since if-then-else forms an expression instead of a statement in those languages.
The operator allows for initializing a variable via a single statement which otherwise might require multiple statements. Use in variable assignment reduces the probability of a bug from a faulty assignment as the assigned variable is stated only once.
For example, in Python:
x: str = 'foo' if b else 'bar'
instead of:
x: str
if b:
x = 'foo'
else:
x = 'bar'
In a language with block scope, a variable must be declared before the if-else statement. For example:
std::string s;
if else
Use of the conditional operator simplifies this:
std::string s = b ? "foo" : "bar";
Furthermore, since initialization is now part of the declaration, rather than a separate statement, the identifier can be a constant. For example:
const std::string s = b ? "foo" : "bar";
Case selector
The conditional operator can be used for case selectors. For example:vehicle = arg 'B' ? bus :
arg 'A' ? airplane :
arg 'T' ? train :
arg 'C' ? car :
arg 'H' ? horse :
feet;
Variations
The syntax and semantics of the operator vary by language.Major differences include whether the expressions can have side effects and whether the language provides short-circuit evaluation semantics, whereby only the selected expression is evaluated.
If a language supports expressions with side effects but does not specify short-circuit evaluation, then a further distinction exists about which expression evaluates first. If no order is guaranteed, a distinction exists about whether the result is then classified as indeterminate or undefined.
If a language does not permit side-effects in expressions, then the order of evaluation has no value semantics though it may yet bear on whether an infinite recursion terminates, or have other performance implications.
For these reasons, in some languages the statement form can have subtly different semantics than the block conditional form.
In almost all languages, the ternary operator is right associative, so that evaluates intuitively as. This means it can be chained similarly to an
if... else if... else if... else chain. The main exception is PHP, in which it was left-associative prior to version 8, and is non-associative thereafter.Furthermore, in all C-family languages and many others, the ternary conditional operator has low operator precedence.
Equivalence to map
The ternary operator can also be viewed as a binary map operation.In R—and other languages with literal expression tuples—one can simulate the ternary operator with something like the R expression .
Nested ternaries can be simulated as where the function returns the index of the first true value in the condition vector. Note that both of these map equivalents are binary operators, revealing that the ternary operator is ternary in syntax, rather than semantics. These constructions can be regarded as a weak form of currying based on data concatenation rather than function composition.
If the language provides a mechanism of futures or promises, then short-circuit evaluation can sometimes also be simulated in the context of a binary map operation.
Examples
Ada
The 2012 edition of Ada has introduced conditional expressions, as part of an enlarged set of expressions including quantified expressions and expression functions. The Rationale for Ada 2012 states motives for Ada not having had them before, as well as motives for now adding them, such as to support "contracts".Pay_per_Hour := ;
When the value of an if_expression is itself of Boolean type, then the part may be omitted, the value being True. Multiple conditions may chained using.
ALGOL 60
ALGOL 60 introduced conditional expressions to imperative programming languages.This conditional statement:
integer opening_time;
if day = Sunday then
opening_time := 12;
else
opening_time := 9;
Can be rewritten with the conditional operator:
integer opening_time;
opening_time := if day = Sunday then 12 else 9;
ALGOL 68
Both ALGOL 68's choice clauses support the following:; Single if choice clause: or a brief form:
; Chained if choice clause: or a brief form:
.Bash
A true ternary operator only exists for arithmetic expressions:)
For strings there only exist workarounds, like e.g.:
result=$
Where can be any condition construct can evaluate. Instead of the there can be any other bash command. When it exits with success, the first echo command is executed, otherwise the second one is executed.
C family
The following code in C assigns to the value ofx if a > b, and otherwise to the value of y. This is the same syntax as in many related languages including C++, Java, JavaScript, and Dart.result = a > b ? x : y;
Only the selected expression is evaluated. In this example,
x and y require no evaluation, but they can be expressions with side effects. Only the side-effect for the selected expression value will occur.ISO.IEC 9899:1999 6.5.15.4If
x and y are of the same data type, the conditional expression generally has that type. Otherwise, the rules governing the resulting data type vary a little between languages:- In C++, the usual arithmetic type conversions are performed to convert
xandyto a common type. If both are pointer or reference types, or one is a pointer type and the other is a constant expression evaluating to 0, pointer or reference conversions are performed to convert them to a common type. - In C#, if one expression is implicitly convertible to the type of the other, that type is used. Otherwise, a compile-time error occurs.
- In dynamically typed languages, the evaluated expression has the type of the selected expression.
x and y are lvalues, though this is rarely used in practice:= frink;
Common Lisp
Assignment using a conditional expression in Common Lisp:Alternative form:
)
dBASE
In dBase, the conditional functioniif is called "Immediate IF". It uses shortcut evaluation.For example, to sort a list by the street name and then house number, one could type
to indexfile
at the dBASE III command prompt, and then copy or export the table.
Fortran
As part of the Fortran-90 Standard, the ternary operator was added to Fortran as the intrinsic function :variable = merge
Note that both x and y are evaluated before the results of one or the other are returned from the function. Here, x is returned if the condition holds true and y otherwise.
Fortran-2023 added conditional expressions which evaluate one or the other of the expressions based on the conditional expression:
variable =
Kotlin
Kotlin does not include the traditional ternary operator, however, an can be used as an expression that can be assigned, achieving the same results.val max = if a else b
Lua
Lua does not have a traditional conditional operator. However, the short-circuiting behavior of its and operators allows the emulation of this behaviour. The following is equivalent to:var = cond ? a : b.var = cond and a or b
This will succeed unless is logically false; in this case, the expression will always result in. This can result in some surprising behavior if ignored.
There are also other variants that can be used, but they're generally more verbose:
var =
Luau, a dialect of Lua, has ternary expressions that look like if statements, but unlike them, they have no keyword, and the clause is required. One may optionally add clauses. It's designed to replace the idiom and is expected to work properly in all cases.
-- in Luau
var = if cond then a else b
-- with elseif clause
sign = if var < 0 then -1 elseif var 0 then 0 else 1