In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, the ternary conditional operator is a
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 operato ...
that is part of the syntax for basic
conditional expressions
Conditional (if then) may refer to:
* Causal conditional, if X then Y, where X is a cause of Y
*Conditional probability, the probability of an event A given that another event B has occurred
* Conditional proof, in logic: a proof that asserts a ...
in several
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 l ...
s. It is commonly referred to as the conditional operator, ternary if, or inline if (abbreviated iif). An expression evaluates to if the value of is true, and otherwise to . One can read it aloud as "if a then b otherwise c". The form is by far and large the most common, but alternative syntaxes do exist; for example,
Raku uses the syntax to avoid confusion with the infix operators and , whereas in
Visual Basic .NET
Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Vi ...
, it instead takes the form .
It originally comes from
CPL, in which equivalent syntax for
''e''1 ? ''e''2 : ''e''3
was
''e''1 → ''e''2, ''e''3
.
Although many ternary operators are possible, the conditional operator is so common, and other ternary operators so rare, that the conditional operator is commonly referred to as ''the'' ternary operator.
Variations
The detailed semantics of "the" ternary operator as well as its syntax differs significantly from language to language.
A top level distinction from one language to another is whether the expressions permit
side effects
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
(as in most procedural languages) and whether the language provides
short-circuit evaluation
A short circuit (sometimes abbreviated to short or s/c) is an electrical circuit that allows a current to travel along an unintended path with no or very low electrical impedance. This results in an excessive current flowing through the circuit ...
semantics, whereby only the selected expression is evaluated (most standard operators in most languages evaluate all arguments).
If the language supports expressions with side effects but does not specify short-circuit evaluation, then a further distinction exists about which expression evaluates first—if the language guarantees any specific order (bear in mind that the conditional also counts as an expression).
Furthermore, if no order is guaranteed, a distinction exists about whether the result is then classified as indeterminate (the value obtained from ''some'' order) or
undefined (any value at all at the whim of the compiler in the face of side effects, or even a crash).
If the language does not permit side-effects in expressions (common in functional languages), 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 (in a functional language with match expressions, short-circuit evaluation is inherent, and natural uses for the ternary operator arise less often, so this point is of limited concern).
For these reasons, in some languages the statement form can have subtly different semantics than the block conditional form (in the C language—the syntax of the example given—these are in fact equivalent).
The associativity of nested ternary operators can also differ from language to language. In almost all languages, the ternary operator is
right associative
In programming language theory, the associativity of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses. If an operand is both preceded and followed by operators (for example ...
so that evaluates intuitively as , but
PHP
PHP is a General-purpose programming language, 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 implementati ...
in particular is notoriously left-associative, and evaluates as follows: , which is rarely what any programmer expects. (The given examples assume that the ternary operator has low
operator precedence
In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression.
For exam ...
, which is true in all C-family languages, and many others.)
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 (this idiom is slightly more natural in languages with 0-origin subscripts)
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
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 tha ...
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.
Conditional assignment
is used as follows:
: ''condition'' ? ''value_if_true'' : ''value_if_false''
The ''condition'' is evaluated ''true'' or ''false'' as a
Boolean expression
In computer science, a Boolean expression is an expression used in programming languages that produces a Boolean value when evaluated. A Boolean value is either true or false. A Boolean expression may be composed of a combination of the Boolean con ...
. On the basis of the evaluation of the Boolean condition, the entire expression returns ''value_if_true'' if ''condition'' is true, but ''value_if_false'' otherwise. Usually the two sub-expressions ''value_if_true'' and ''value_if_false'' must have the same type, which determines the type of the whole expression. The importance of this type-checking lies in the operator's most common use—in
conditional
Conditional (if then) may refer to:
* Causal conditional, if X then Y, where X is a cause of Y
* Conditional probability, the probability of an event A given that another event B has occurred
*Conditional proof, in logic: a proof that asserts a ...
assignment statements. In this usage it appears as an
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, ...
on the right side of an assignment
statement, as follows:
: ''variable'' = ''condition'' ? ''value_if_true'' : ''value_if_false''
The ?: operator is similar to the way conditional expressions (if-then-else constructs) work in
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
languages, like
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 ...
,
ML, and
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 lan ...
, since if-then-else forms an expression instead of a statement in those languages.
Usage
The conditional operator's most common usage is to make a terse simple conditional assignment statement. For example, if we wish to implement some C code to change a shop's normal opening hours from 9 o'clock to 12 o'clock on Sundays, we may use
int opening_time = (day SUNDAY) ? 12 : 9;
instead of the more verbose
int opening_time;
if (day SUNDAY)
opening_time = 12;
else
opening_time = 9;
The two forms are nearly equivalent. Keep in mind that the is an expression and
if-then-else
In computer science, conditionals (that is, conditional statements, conditional expressions and conditional constructs,) are programming language commands for handling decisions. Specifically, conditionals perform different computations or actio ...
is a statement. Note that neither the ''true'' nor ''false'' portions can be omitted from the conditional operator without an error report upon parsing. This contrasts with if-then-else statements, where the else clause can be omitted.
Most of the languages emphasizing
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
don't need such an operator as their regular conditional expression(s) is an expression in the first place e.g. the
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 ...
expression is equivalent in semantics to the C expression . This is also the case in many imperative languages, starting with
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 th ...
where it is possible to write , or
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 ...
() or
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
(, although works as well).
Note that some languages may evaluate ''both'' the true- and false-expressions, even though only one or the other will be assigned to the variable. This means that if the true- or false-expression contain a function call, that function may be called and executed (causing any related side-effects due to the function's execution), regardless of whether or not its result will be used. Programmers should consult their programming language specifications or test the ternary operator to determine whether or not the language will evaluate both expressions in this way. If it does, and this is not the desired behaviour, then an
if-then-else statement should be used.
ActionScript 3
condition ? value_if_true : value_if_false
Ada
The 2012 edition of
Ada has introduced conditional expressions (using and ), 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" (also new).
Pay_per_Hour := (if Day = Sunday
then 12.50
else 10.00);
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 68
Both
ALGOL 68
ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously ...
's
choice clauses (if and the case clauses) provide the coder with a choice of ''either'' the "bold" syntax or the "''brief''" form.
* Single if choice clause:
if condition then statements
else statements fi
"''brief''" form: ( condition , statements , statements )
* Chained if choice clause:
if condition1 then statements elif condition2 then statements
else statements fi
"''brief''" form: ( condition1 , statements , : condition2 , statements , statements )
APL
With the following syntax, both expressions are evaluated (with evaluated first, then , then ):
result ← value_if_true ⊣⍣ condition ⊢ value_if_false
This alternative syntax provides short-circuit evaluation:
result ← ⍬
AWK
result = condition ? value_if_true : value_if_false
Bash
A true ternary operator only exists for arithmetic expressions:
((result = condition ? value_if_true : value_if_false))
For strings there only exist workarounds, like e.g.:
result=$( "$a" = "$b" && echo "value_if_true" , , echo "value_if_false")
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
A traditional if-else construct in
C is written:
if (a > b)
else
This can be rewritten as the following statement:
result = a > b ? x : y;
As in the if-else construct only one of the expressions 'x' and 'y' is evaluated. This is significant if the evaluation of 'x' or 'y' has
side effect
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
s.
[ISO.IEC 9899:1999 (E) 6.5.15.4] The behaviour is undefined if an attempt is made to use the result of the conditional operator as an
lvalue.
A
GNU
GNU () is an extensive collection of free software
Free software or libre software is computer software distributed under terms that allow users to run the software for any purpose as well as to study, change, and distribute it and any ...
extension to C allows omitting the second operand, and using implicitly the first operand as the second also:
a x ? : y;
The expression is equivalent to
a x ? (a x) : y;
except that if ''x'' is an expression, it is evaluated only once. The difference is significant if evaluating the expression has side effects. This shorthand form is sometimes known as the
Elvis operator
In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. This is ident ...
in other languages.
C#
In
C#, if condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. As with
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 mo ...
only one of two expressions is ever evaluated.
// condition ? first_expression : second_expression;
static double sinc(double x)
C++
Unlike in
C, the precedence of the operator in
C++ is the same as that of the assignment operator ( or ), and it can return an lvalue. This means that expressions like and are both legal and are parsed differently, the former being equivalent to .
In
C++ there are conditional assignment situations where use of the ''if-else'' statement is impossible, since this language explicitly distinguishes between
initialization and
assignment. In such case it is always possible to use a function call, but this can be cumbersome and inelegant. For example, to pass conditionally different values as an argument for a constructor of a field or a base class, it is impossible to use a plain ''if-else'' statement; in this case we can use a conditional assignment expression, or a function call. Bear in mind also that some types allow initialization, but do not allow assignment, or even that the assignment operator and the constructor do totally different things. This last is true for reference types, for example:
#include
#include
#include
int main(int argc, char *argv[])
In this case there is no possibility of using an if-else statement in place of the operator (Although we can replace the use of with a function call, inside of which can be an ''if-else'' statement).
Furthermore, the conditional operator can yield an lvalue, i.e. a value to which another value can be assigned. Consider the following example:
#include
int main(int argc, char *argv[])
In this example, if the boolean expression yields the value on line 8, the value is assigned to the variable , otherwise the value is assigned to the variable .
In C++ and other various languages, ternary operators like are also possible but are very rare.
CFML
Example of the operator in
CFML
ColdFusion Markup Language, more commonly known as CFML, is a scripting language for web development that runs on the JVM, the .NET framework, and Google App Engine. Multiple commercial and open source implementations of CFML engines are availa ...
:
result = randRange(0,1) ? "heads" : "tails";
Roughly 50% of the time the expression will return 1 (true) or 0 (false); meaning result will take the value "heads" or "tails" respectively.
Lucee, Railo, and ColdFusion 11-specific
Lucee
Lucee is an open source implementation of a lightweight dynamically-typed scripting language for the Java virtual machine (JVM).
The language is used for rapid development of web applications that compile directly to Java bytecode, and is compa ...
,
Railo
Railo Server, commonly referred to as Railo ( ), is open source software which implements the general-purpose CFML server-side scripting language, often used to create dynamic websites, web applications and intranet systems. CFML is a dynami ...
, and ColdFusion 11 also implement the Elvis operator, which will return the value of the expression if it is not-null, otherwise the specified default.
Syntax:
result = expression ?: value_if_expression_is_null
Example:
result = f() ?: "default";
// where...
function f()
writeOutput(result);
The function will return roughly 50% of the time, otherwise will not return anything. If returns "value", will take that value, otherwise will take the value "default".
CoffeeScript
Example of using this operator in
CoffeeScript
CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehen ...
:
if 1 is 2 then "true value" else "false value"
Returns "false value".
Common Lisp
Assignment using a conditional expression in
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 fr ...
:
(setq result (if (> a b) x y))
Alternative form:
(if (> a b)
(setq result x)
(setq result y))
Crystal
Example of using this operator in
Crystal
A crystal or crystalline solid is a solid material whose constituents (such as atoms, molecules, or ions) are arranged in a highly ordered microscopic structure, forming a crystal lattice that extends in all directions. In addition, macr ...
:
1 2 ? "true value" : "false value"
Returns .
The Crystal compiler transforms conditional operators to expressions, so the above is semantically identical to:
if 1 2
"true value"
else
"false value"
end
Dart
The
Dart
Dart or DART may refer to:
* Dart, the equipment in the game of darts
Arts, entertainment and media
* Dart (comics), an Image Comics superhero
* Dart, a character from ''G.I. Joe''
* Dart, a ''Thomas & Friends'' railway engine character
* D ...
programming language's syntax belongs to the
C family, primarily inspired by languages like Java, C# and JavaScript, which means it has inherited the traditional syntax for its conditional expression.
Example:
return x.isEven ? x ~/ 2 : x * 3 + 1;
Like other conditions in Dart, the expression before the must evaluate to a
Boolean value.
The Dart syntax uses both and in various other ways, which causes ambiguities in the language grammar. An expression like:
could be parsed as either a "set literal" containing one of two lists ''or'' as a "map literal"
. The language always chooses the conditional expression in such situations.
Dart also has a second ternary operator, the operator commonly used for setting values in lists or maps, which makes the term "the ternary operator" ambiguous in a Dart context.
Delphi
In
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracl ...
the function can be used to achieve the same as . If the library is used, the function returns a numeric value such as an
Integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language ...
,
Double
A double is a look-alike or doppelgänger; one person or being that resembles another.
Double, The Double or Dubble may also refer to:
Film and television
* Double (filmmaking), someone who substitutes for the credited actor of a character
* Th ...
or Extended. If the library is used, this function can also return a
string
String or strings may refer to:
*String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects
Arts, entertainment, and media Films
* ''Strings'' (1991 film), a Canadian anim ...
value.
Using
function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer): Integer;
function IfThen(AValue: Boolean; const ATrue: Int64; const AFalse: Int64): Int64;
function IfThen(AValue: Boolean; const ATrue: UInt64; const AFalse: UInt64): UInt64;
function IfThen(AValue: Boolean; const ATrue: Single; const AFalse: Single): Single;
function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double): Double;
function IfThen(AValue: Boolean; const ATrue: Extended; const AFalse: Extended): Extended;
Using the library
function IfThen(AValue: Boolean; const ATrue: string; AFalse: string = ''): string;
Usage example:
function GetOpeningTime(Weekday: Integer): Integer;
begin
Result := IfThen((Weekday = 1) or (Weekday = 7), 12, 9);
end;
Unlike a true ternary operator however, both of the results are evaluated prior to performing the comparison. For example, if one of the results is a call to a function which inserts a row into a database table, that function will be called whether or not the condition to return that specific result is met.
F#
In
F# the built-in syntax for if-then-else is already an expression that always must return a value.
let num = if x = 10 then 42 else 24
F# has a special case where you can omit the else branch if the return value is of type unit. This way you can do side-effects, without using a else branch.
if x = 10 then
printfn "It is 10"
But even in this case, the if expression would return unit. You don't need to write the else branch, because the compiler will assume the unit type on else.
FORTH
Since
FORTH
Forth or FORTH may refer to:
Arts and entertainment
* ''forth'' magazine, an Internet magazine
* ''Forth'' (album), by The Verve, 2008
* ''Forth'', a 2011 album by Proto-Kaw
* Radio Forth, a group of independent local radio stations in Scotla ...
is a stack-oriented language, and any expression can leave a value on the stack, all // sequences can generate values:
: test ( n -- n ) 1 AND IF 22 ELSE 42 THEN ;
This word takes 1 parameter on the stack, and if that number is odd, leaves 22. If it's even, 42 is left on the stack.
Fortran
With the additions to the code in the 1995 release, the ternary operator was added to the
Fortran compiler as the intrinsic function :
variable = merge(x,y,a>b)
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.
FreeMarker
This built-in exists since
FreeMarker 2.3.20.
Used like
''booleanExp''?then(''whenTrue'', ''whenFalse'')
, fills the same role as the ternary operator in C-like languages.
<#assign x = 10>
<#assign y = 20>
<#-- Prints the maximum of x and y: -->
$
Go
There is no ternary if in
Go, so use of the full if statement is always required.
Haskell
The built-in if-then-else syntax is inline: the expression
if predicate then expr1 else expr2
has type
Bool -> a -> a -> a
The base library also provides the function :
bool :: a -> a -> Bool -> a
In both cases, no special treatment is needed to ensure that only the selected expression is evaluated, since Haskell is non-strict by default. This also means an operator can be defined that, when used in combination with the operator, functions exactly like in most languages:
(?) :: Bool -> a -> a -> a
(?) pred x y = if pred then x else y
infix 1 ?
-- example (vehicle will evaluate to "airplane"):
arg = 'A'
vehicle = arg 'B' ? "boat" $
arg 'A' ? "airplane" $
arg 'T' ? "train" $
"car"
However, it is more idiomatic to us
pattern guards
-- example (vehicle will evaluate to "airplane"):
arg = 'A'
vehicle , arg 'B' = "boat"
, arg 'A' = "airplane"
, arg 'T' = "train"
, otherwise = "car"
Java
In
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 mo ...
this expression evaluates to:
// If foo is selected, assign selected foo to bar. If not, assign baz to bar.
Object bar = foo.isSelected() ? foo : baz;
Note that Java, in a manner similar to C#, only evaluates the used expression and will not evaluate the unused expression.
[Java 7 Specification]
15.25 Conditional Operator ? :
/ref>
Julia
In Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e ...
, "Note that the spaces around and are mandatory: an expression like is not a valid ternary expression (but a newline is acceptable after both the and the )."
JavaScript
The conditional operator in 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 ...
is similar to that of C++ and 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 mo ...
, except for the fact the middle expression cannot be a comma expression. Also, as in C++, but unlike in C or Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
, it will not bind tighter than an assignment to its right— is equivalent to instead of .
var timeout = settings null ? 1000 : settings.timeout;
Just like C# and Java, the expression will only be evaluated if, and only if, the expression is the matching one for the condition given; the other expression will not be evaluated.
Kotlin
Kotlin does not include the traditional ternary operator, however, s can be used as expressions that can be assigned, achieving the same results. Note that, as the complexity of one's conditional statement grows, the programmer might consider replacing their - expression with a expression.
val max = if (a > b) a else b
Lua
Lua does not have a traditional conditional operator. However, the short-circuiting behaviour of its and operators allows the emulation of this behaviour:
-- equivalent to var = cond ? a : b;
var = cond and a or b
This will succeed unless is logically false (i.e. or ); in this case, the expression will always result in . This can result in some surprising behaviour if ignored.
Objective-C
condition ? value_if_true : value_if_false
int min = (1 < 2) ? 1 : 2;
This will set the variable to because the condition is .
Perl
A traditional if-else construct in Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
is written:
if ($a > $b) else
Rewritten to use the conditional operator:
$result = $a > $b ? $x : $y;
The precedence of the conditional operator in Perl is the same as in C, not as in C++. This is conveniently of higher precedence than a comma operator
In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type); there ...
but lower than the precedence of most operators used in expressions within the ternary operator, so the use of parentheses is rarely required.
Its associativity matches that of C and C++, not that of PHP. Unlike C but like C++, Perl allows the use of the conditional expression as an L-value; for example:
$a > $b ? $x : $y = $result;
will assign to either or depending on the logical expression's boolean result.
The respective precedence rules and associativities of the operators used guarantee that the version absent any parentheses is equivalent to this explicitly parenthesized version:
(($a > $b) ? $x : $y) = $result;
This is equivalent to the if-else version:
if ($a > $b) else
PHP
A simple PHP
PHP is a General-purpose programming language, 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 implementati ...
implementation is this:
$abs = $value >= 0 ? $value : -$value;
Unlike most other programming languages, the conditional operator in PHP
PHP is a General-purpose programming language, 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 implementati ...
is left associative rather than right associative. Thus, given a value of T for arg, the PHP code in the following example would yield the value horse instead of train as one might expect:
'B' ) ? 'bus' :
( $arg 'A' ) ? 'airplane' :
( $arg 'T' ) ? 'train' :
( $arg 'C' ) ? 'car' :
( $arg 'H' ) ? 'horse' :
'feet' );
echo $vehicle;
The reason is that nesting two conditional operators produces an oversized condition with the last two options as its branches: is really . This is acknowledged and will probably not change. To avoid this, nested parenthesis are needed, as in this example:
"B" ? "bus" :
($arg "A" ? "airplane" :
($arg "T" ? "train" :
($arg "C" ? "car" :
($arg "H" ? "horse" :
"feet"))));
echo $vehicle;
This will produce the result of train being printed to the output, analogous to a right associative conditional operator.
Python
Though it had been delayed for several years by disagreements over syntax, an operator for a conditional expression in Python was approved a
Python Enhancement Proposal 308
and was added to the 2.5 release in September 2006. Python's conditional operator differs from the common operator in the order of its operands. The general form is:
result = x if a > b else y
This form invites considering as the normal value and as an exceptional case.
Prior to Python 2.5 there were a number of ways to approximate a conditional operator (for example by indexing into a two element array), all of which have drawbacks as compared to the built-in operator.
R
The traditional if-else construct in R (which is an implementation of S) is:
if (a < b) else
If there is only one statement in each block, braces can be omitted, like in C:
if (a < b)
x <- "true"
else
x <- "false"
The code above can be written in the following non-standard condensed way:
x <- if (a < b) "true" else "false"
There exists also the function that allows rewriting the expression above as:
x <- ifelse(a < b, "true", "false")
The function is automatically vectorized. For instance:
> ifelse(c (0, 2) < 1, "true", "false")
"true" "false"
Raku
Raku uses a doubled symbol instead of single
and a doubled symbol instead of
$result = $a > $b ?? $x !! $y;
Ruby
Example of using this operator in Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
:
1 2 ? "true value" : "false value"
Returns "false value".
A traditional if-else construct in Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
is written:[Programming Ruby]
Conditional Execution
/ref>
if a > b
result = x
else
result = y
end
This could also be written as:
result = if a > b
x
else
y
end
These can be rewritten as the following statement:
result = a > b ? x : y
Rust
Being an expression-oriented programming language
An expression-oriented programming language is a programming language in which every (or nearly every) construction is an expression and thus yields a value. The typical exceptions are macro definitions, preprocessor commands, and declarations ...
, Rust's existing if ''expr1'' else ''expr2''
syntax can behave as the traditional ternary operator does. Earlier versions of the language did have the operator but it was removed due to duplication with .
Note the lack of semi-colons in the code below compared to a more declarative ... block, and the semi-colon at the end of the assignment to .
let x = 5;
let y = if x 5 else ;
This could also be written as:
let y = if x 5 else ;
Note that curly braces are mandatory in Rust conditional expressions.
You could also use a expression:
let y = match x ;
Scheme
Same as in Common Lisp. Every expression has a value. Thus the builtin can be used:
(let* ((x 5)
(y (if (= x 5) 10 15)))
...)
Smalltalk
Every expression (message send) has a value. Thus can be used:
, x y,
x := 5.
y := (x 5) ifTrue: 0ifFalse: 5
SQL
The SQL expression is a generalization of the ternary operator. Instead of one conditional and two results, ''n'' conditionals and ''n+1'' results can be specified.
With one conditional it is equivalent (although more verbose) to the ternary operator:
SELECT (CASE WHEN a > b THEN x ELSE y END) AS CONDITIONAL_EXAMPLE
FROM tab;
This can be expanded to several conditionals:
SELECT (CASE WHEN a > b THEN x WHEN a < b THEN y ELSE z END) AS CONDITIONAL_EXAMPLE
FROM tab;
MySQL
In addition to the standard expression, MySQL provides an function as an extension:
IF(cond, a, b);
SQL Server
In addition to the standard expression, SQL Server (from 2012) provides an function:
IIF(condition, true_value, false_value)
Oracle SQL
In addition to the standard expression, Oracle has a variadic function
In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.
The term ''var ...
al counterpart which operates similarly to a 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 som ...
and can be used to emulate the conditional operator when testing for equality.
-- General syntax takes case-result pairs, comparing against an expression, followed by a fall-back result:
DECODE(expression, case1, result1,
...
caseN, resultN,
resultElse)
-- We can emulate the conditional operator by just selecting one case:
DECODE(expression, condition, true, false)
The function is, today, deprecated in favour of the standard expression. This can be used in both Oracle SQL queries as well as PL/SQL
PL/SQL (Procedural Language for SQL) is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 6 - stored PL/SQL procedures/functions/packages/triggers since ...
blocks, whereas can only be used in the former.
Swift
The ''ternary conditional operator'' of Swift is written in the usual way of the C tradition, and is used within expressions.
let result = a > b ? a : b
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 ...
, this operator is available in expr
expressions only:
set x 5
set y xpr
Outside of expr
, if
can be used for a similar purpose, as it also returns a value:
package require math
set x 5
set y f else
F, or f, is the sixth letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''ef'' (pronounced ), and the plural is ''efs''.
Hist ...
TestStand
In
National Instruments TestStand
expression, if condition is true, the first expression is evaluated and becomes the output of the conditional operation; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.
condition ? first_expression : second_expression
For example:
RunState.Root.Parameters.TestSocket.Index 3 ? Locals.UUTIndex = 3 : Locals.UUTIndex = 0
Sets the local variable to 3 if is 3, otherwise it sets to 0.
Similar to other languages, first_expression and second_expression do not need to be autonomous expressions, allowing the operator to be used for variable assignment:
Locals.UUTIndex = ( RunState.Root.Parameters.TestSocket.Index 3 ? 3 : 0 )
Verilog
Verilog
Verilog, standardized as IEEE 1364, is a hardware description language (HDL) used to model electronic systems. It is most commonly used in the design and verification of digital circuits at the register-transfer level of abstraction. It is a ...
is technically a hardware description language
In computer engineering, a hardware description language (HDL) is a specialized computer language used to describe the structure and behavior of electronic circuits, and most commonly, digital logic circuits.
A hardware description language e ...
, not a programming language though the semantics of both are very similar. It uses the syntax for the ternary operator.
// using blocking assignment
wire out;
assign out = sel ? a : b;
This is equivalent to the more verbose Verilog code:
// using blocking assignment
wire out;
if (sel 1) // sel is 1, not 0, x or z
assign out = a;
else if (sel 0) // sel is 0, x or z (1 checked above)
assign out = b;
else // sel is x or z (0 and 1 checked above)
assign out = omment // a and b are compared bit by bit, and return for each bit
// an x if bits are different, and the bit value if the same
Visual Basic
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 (c ...
doesn't use per se, but has a very similar implementation of this shorthand statement. Using the first example provided in this article, it can do:
' variable = IIf(condition, value_if_true, value_if_false)
Dim opening_time As Integer = IIf((day = SUNDAY), 12, 9)
In the above example, is a ternary function, but not a ternary operator. As a function, the values of all three portions are evaluated before the function call occurs. This imposed limitations, and in Visual Basic .Net 9.0, released with Visual Studio 2008, an actual conditional operator was introduced, using the keyword instead of . This allows the following example code to work:
Dim name As String = If(person Is Nothing, "", person.Name)
Using , would be evaluated even if person is (Nothing), causing an exception. With a true short-circuiting conditional operator, is not evaluated unless person is not .
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 (c ...
Version 9 has added the operator in addition to the existing function that existed previously. As a true operator, it does not have the side effects and potential inefficiencies of the function.
The syntaxes of the tokens are similar: vs . As mentioned above, the function call has significant disadvantages, because the sub-expressions must all be evaluated, according to Visual Basic's evaluation strategy
In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the f ...
for function calls and the result will always be of type variant (VB) or object (VB.NET). The operator however does not suffer from these problems as it supports conditional evaluation and determines the type of the expression based on the types of its operands.
Result type
Clearly the type of the result of the operator must be in some sense the type unification
Type may refer to:
Science and technology Computing
* Typing, producing text via a keyboard, typewriter, etc.
* Data type, collection of values used for computations.
* File type
* TYPE (DOS command), a command to display contents of a file.
* Typ ...
of the types of its second and third operands. In C this is accomplished for numeric type
A number is a mathematical object used to count, measure, and label. The original examples are the natural numbers 1, 2, 3, 4, and so forth. Numbers can be represented in language with number words. More universally, individual numbers can ...
s by arithmetic promotion
Arithmetic () is an elementary part of mathematics that consists of the study of the properties of the traditional operations on numbers—addition, subtraction, multiplication, division, exponentiation, and extraction of roots. In the 19th cen ...
; since C does not have a type hierarchy
A class hierarchy or inheritance tree in computer science is a classification of object types, denoting objects as the instantiations of Class (computer programming), classes (class is like a blueprint, the object is what is built from that bluepr ...
for pointer
Pointer may refer to:
Places
* Pointer, Kentucky
* Pointers, New Jersey
* Pointers Airport, Wasco County, Oregon, United States
* The Pointers, a pair of rocks off Antarctica
People with the name
* Pointer (surname), a surname (including a list ...
types, pointer operands may only be used if they are of the same type (ignoring type qualifier In the C, C++, and D programming languages, a type qualifier is a keyword that is applied to a type, resulting in a ''qualified type.'' For example, const int is a qualified type representing a constant integer, while int is the corresponding u ...
s) or one is void
Void may refer to:
Science, engineering, and technology
* Void (astronomy), the spaces between galaxy filaments that contain no galaxies
* Void (composites), a pore that remains unoccupied in a composite material
* Void, synonym for vacuum, a ...
or NULL
Null may refer to:
Science, technology, and mathematics Computing
*Null (SQL) (or NULL), a special marker and keyword in SQL indicating that something has no value
*Null character, the zero-valued ASCII character, also designated by , often used ...
. It is undefined behaviour
In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres. This is different from unspecified behavior, ...
to mix pointer and integral or incompatible pointer types; thus
number = spell_out_numbers ? "forty-two" : 42;
will result in a compile-time error
In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled.
The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concep ...
in most compilers.
?: in style guidelines
Conditional operators are widely used and can be useful in certain circumstances to avoid the use of an statement, either because the extra verbiage would be too lengthy or because the syntactic context does not permit a statement. For example:
#define MAX(a, b) (((a)>(b)) ? (a) : (b))
or
for (i = 0; i < MAX_PATTERNS; i++)
c_patterns ShowWindow(m_data.fOn ? SW_SHOW : SW_HIDE);
(The latter example uses the Microsoft Foundation Classes
Microsoft Foundation Class Library (MFC) is a C++ object-oriented library for developing desktop applications for Windows.
MFC was introduced by Microsoft in 1992 and quickly gained widespread use. While Microsoft has introduced alternative ap ...
Framework for Win32
The Windows API, informally WinAPI, is Microsoft's core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. The name Windows API collectively refers to several different platform implementations ...
.)
Initialization
An important use of the conditional operator is in allowing a single initialization statement, rather than multiple initialization statements. In many cases this also allows single assignment
In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages, the as ...
and for an identifier to be a constant.
The simplest benefit is avoiding duplicating the variable name, as in Python:
x = 'foo' if b else 'bar'
instead of:
if b:
x = 'foo'
else:
x = 'bar'
More importantly, in languages with block scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
, such as C++, the blocks of an if/else statement create new scopes, and thus variables must be declared ''before'' the if/else statement, as:
std::string s;
if (b)
s = "foo";
else
s = "bar";
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 (formally, of type):
const std::string s = b ? "foo" : "bar";
Case selectors
When properly formatted, the conditional operator can be used to write simple and coherent case selectors. For example:
vehicle = arg 'B' ? bus :
arg 'A' ? airplane :
arg 'T' ? train :
arg 'C' ? car :
arg 'H' ? horse :
feet;
Appropriate use of the conditional operator in a variable assignment context reduces the probability of a bug from a faulty assignment as the assigned variable is stated just once as opposed to multiple times.
Programming languages without the conditional operator
The following are examples of notable general-purpose programming languages that don't provide a conditional operator:
* CoffeeScript
CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehen ...
* Go programming language
* MATLAB
MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementa ...
* Pascal although Object Pascal / Delphi do have a function to do the same (with caveats)
* 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), ...
The construct is an expression and can be used to get the same functionality.
*
* PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sou ...
(in old versions) an elegant workaround is to use ('''','''') '')">('''')/code>
See also
* IIf
In computing, IIf (an abbreviation for Immediate if) is a function in several editions of the Visual Basic programming language and ColdFusion Markup Language (CFML), and on spreadsheets that returns the second or third parameter based on the e ...
, inline if function
* Null coalescing operator
The null coalescing operator (called the Logical Defined-Or operator in Perl) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#, PowerShell as of version 7.0.0, Perl ...
, operator
* Elvis operator
In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. This is ident ...
, , or sometimes , as a shorthand binary operator
In mathematics, a binary operation or dyadic operation is a rule for combining two elements (called operands) to produce another element. More formally, a binary operation is an operation of arity two.
More specifically, an internal binary op ...
* Conditioned disjunction
In logic, conditioned disjunction (sometimes called conditional disjunction) is a ternary logical connective introduced by Church. Given operands ''p'', ''q'', and ''r'', which represent truth-valued propositions, the meaning of the conditioned di ...
, equivalent ternary logical connective.
References
{{reflist, 2
External links
Description of If operator in Visual Basic
Description of Conditional Expression in Python (PEP 308)
Description in the Java Language Specification
Description in the PHP Language Documentation
Conditional constructs
Operators (programming)
Ternary operations
Articles with example code
de:Bedingte Anweisung und Verzweigung#Auswahloperator