ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.6 months ago (distributed domain, exempt) |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://en.wikipedia.org/wiki/Ternary_conditional_operator |
| Last Crawled | 2026-03-21 03:40:31 (16 days ago) |
| First Indexed | 2021-08-27 05:43:06 (4 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Ternary conditional operator - Wikipedia |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | "?:" redirects here. For use as a binary operator, see
Elvis operator
.
"Conditional operator" redirects here. For the
||
and
&&
operators, sometimes called conditional operators in Java and C#, see
Short-circuit evaluation
.
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
(
iif
). 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
if a then b else c
or
a ? b : c
. One can read it aloud as "if a then b otherwise c". The form
a ? b : c
is the most common, but alternative syntax exists. For example,
Raku
uses the syntax
a ?? b !! c
to avoid confusion with the infix operators
?
and
!
, whereas in
Visual Basic
, it takes the form
If(a, b, c)
.
The construct first appeared in
CPL
, in which equivalent syntax for
a ? b : c
is
a → b, c
.
[
1
]
[
2
]
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 (if-then-else) 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
(
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. For example:
const
std
::
string
s
=
b
?
"foo"
:
"bar"
;
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
;
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 (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 a 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
r = condition ? expr1 : expr2
can have subtly different semantics than the block conditional form
if
(
condition
)
{
r
=
expr1
;
}
else
{
r
=
expr2
;
}
.
In almost all languages, the ternary operator is
right associative
, so that
a == 1 ? "one" : a == 2 ? "two" : "many"
evaluates intuitively as
a == 1 ? "one" : (a == 2 ? "two" : "many")
. 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 (such that the same expression evaluates to
(a == 1 ? "one" : a == 2) ? "two" : "many"
, which is rarely what the programmer expects)
[
3
]
prior to version 8, and is non-associative thereafter.
[
4
]
Furthermore, in all C-family languages and many others, the ternary conditional operator has low
operator precedence
.
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
c
(
expr1
,
expr2
)[
1
+
condition
]
(this idiom is slightly more natural in languages with 0-origin subscripts).
Nested ternaries can be simulated as
c
(
expr1
,
expr2
,
expr3
)[
which.first
((
c
(
cond1
,
cond2
,
TRUE
))]
where the function
which.first
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.
The 2012 edition of
Ada
has introduced conditional expressions (using
if
and
case
), as part of an enlarged set of expressions including quantified expressions and expression functions. The Rationale for Ada 2012
[
5
]
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
else
part may be omitted, the value being True. Multiple conditions may chained using
elsif
.
ALGOL 60 introduced
conditional expressions
(ternary conditionals) 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
;
Both
ALGOL 68
's
choice clauses
(if and case clauses) support the following:
Single if choice clause
if condition then statements [ else statements ] fi
or a brief form:
( condition | statements | statements )
Chained if choice clause
if condition1 then statements elif condition2 then statements [ else statements ] fi
or a brief form:
( condition1 | statements |: condition2 | statements | statements )
.
A true ternary operator exists for arithmetic expressions:
((
result
=
condition
?
value_if_true
:
value_if_false
))
For strings there are workarounds, like e.g.:
result
=
$(if
condition
;
then
echo
"value_if_true"
;
else
echo
"value_if_false"
;
fi)
Where
condition
can be any bash command. When it exits with success, the first echo command is executed, otherwise the second one is executed.
The following code in
C
assigns
result
to the value of
x
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.
[
6
]
[
7
]
If
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
x
and
y
to 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.
[
8
]
In C#, if one expression is implicitly convertible to the type of the other, that type is used. Otherwise, a compile-time error occurs.
[
9
]
In dynamically typed languages, the evaluated expression has the type of the selected expression.
Furthermore, in C++, a conditional expression can be used as an
lvalue
, if both
x
and
y
are lvalues, though this is rarely used in practice:
[
10
]
(
foo
?
bar
:
baz
)
=
frink
;
Assignment using a conditional expression in
Common Lisp
:
(
setq
result
(
if
(
>
a
b
)
x
y
))
Alternative form:
(
if
(
>
a
b
)
(
setq
result
x
)
(
setq
result
y
))
In
dBase
, the conditional function
iif(<expL>, <expT>, <expF>)
is called "Immediate IF". It uses shortcut evaluation (it only evaluates one of
<expT>
or
<expF>
).
For example, to sort a list by the street name and then (in most cases) house number, one could type
index
on
iif
(in
str
(addr,
" "
) ,
substr
(addr,in
str
(addr,
" "
)+1,10) +
left
(addr,in
str
(addr,
" "
)-1) , addr)
to indexfile
at the dBASE III command prompt, and then copy or export the table.
As part of the Fortran-90 Standard, the ternary operator was added to
Fortran
as the intrinsic function
merge
:
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.
Fortran-2023 added conditional expressions which evaluate one or the other of the expressions based on the conditional expression:
variable
=
(
a
>
b
?
x
:
y
)
Kotlin does not include the traditional
?:
ternary operator, however, an
if
can be used as an expression that can be assigned,
[
11
]
achieving the same results.
val
max
=
if
(
a
>
b
)
a
else
b
Lua does not have a traditional conditional operator. However, the short-circuiting behavior of its
and
and
or
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
a
is logically false; in this case, the expression will always result in
b
. 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
=
(
{
[
true
]
=
a
,
[
false
]
=
b
}
)[
not
not
cond
]
Luau, a dialect of Lua, has ternary expressions that look like if statements, but unlike them, they have no
end
keyword, and the
else
clause is required. One may optionally add
elseif
clauses. It's designed to replace the
cond
and
a
or
b
idiom and is expected to work properly in all cases.
[
12
]
-- 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
Pascal was both a simplification and extension of ALGOL 60 (mainly for handling user-defined types).
One simplification was to remove the conditional expression since the same could be achieved with the less succinct conditional statement form.
RemObjects Oxygene
added a ternary operator to Object Pascal in approximately 2011,
[
13
]
and in 2025 Delphi followed suit.
[
14
]
Oxygene supports
case/switch statements
, essentially a repeated if, as expressions evaluating to a value as well.
[
15
]
An operator for a conditional expression in
Python
was approved as
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:
[
16
]
result
=
x
if
a
>
b
else
y
This form invites considering
x
as the normal value and
y
as an exceptional case.
Being an
expression-oriented programming language
, Rust's existing
if
expr
1
else
expr
2
syntax can behave as the traditional
?:
ternary operator does. Earlier versions of the language did have the
?:
operator but it was removed
[
17
]
due to duplication with
if
.
[
18
]
Note the lack of semi-colons in the code below compared to a more declarative
if
...
else
block, and the semi-colon at the end of the assignment to
y
.
let
x
=
5
;
let
y
=
if
x
==
5
{
10
}
else
{
15
};
This could also be written as:
let
y
=
if
x
==
5
{
10
}
else
{
15
};
Note that curly braces are mandatory in Rust conditional expressions.
You could also use a
match
expression:
let
y
=
match
x
{
5
=>
10
,
_
=>
15
,
};
Every expression (message send) has a value. Thus
ifTrue:ifFalse:
can be used:
|x
y|
x
:=
5.
y
:=
(
x
==
5
)
ifTrue:
[
10
]
ifFalse:
[
15
]
.
The SQL
CASE
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
;
Visual Basic
provides a ternary conditional function,
IIf
, as shown in the following code:
Dim
opening_time
As
Integer
=
IIf
((
day
=
SUNDAY
),
12
,
9
)
As a function, the values of the three arguments are evaluated before the function is called. To avoid evaluating the expression that is not selected, the
If
keyword was added (in Visual Basic .Net 9.0) as a true ternary conditional operator. This allows the following code to avoid an exception if it were implemented with
IIf
instead:
Dim
name
As
String
=
If
(
person
Is
Nothing
,
""
,
person
.
Name
)
Conditioned disjunction
Elvis operator
– Binary operator in computer programming
McCarthy Formalism
– Computer science and recursion theory
Multiplexer
– Device that selects between several analog or digital input signals
Null coalescing operator
– Binary operator in computer programming
Safe navigation operator
– Boolean operator
Three-way comparison
(one numeric expression selects one of three statements or branches)
^
Strachey, Christopher
(2000). "
Fundamental Concepts in Programming Languages
".
Higher-Order and Symbolic Computation
.
13
(
1–
2):
11–
49.
doi
:
10.1023/A:1010000313106
.
S2CID
14124601
.
^
"5.5 Conditional expressions".
The BCPL Reference Manual
(PDF)
. 1967. pp.
16–
17. Archived from
the original
(PDF)
on 2016-03-16
. Retrieved
2017-03-15
.
^
Wastl, Eric.
"Ternary operator associativity"
.
phpsadness.com
. PHP Sadness
. Retrieved
20 September
2017
.
^
https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
^
"Rationale for Ada 2012"
. ACAA
. Retrieved
10 December
2015
.
^
ISO.IEC 9899:1999 (E) 6.5.15.4
^
Java 7 Specification:
15.25 Conditional Operator ? :
^
mikeblome.
"Conditional Operator: ?"
.
docs.microsoft.com
. Retrieved
2019-04-29
.
^
BillWagner.
"?: Operator - C# Reference"
.
docs.microsoft.com
. Retrieved
2019-04-29
.
^
"Conditional Operator"
.
wiki.c2.com
. Retrieved
2019-04-29
.
^
"Kotlin Lang If Expression"
.
kotlinlang.org
. Retrieved
2021-04-25
.
^
"Syntax § If-then-else expressions"
.
Luau
. Retrieved
2023-02-07
.
^
"if then (else) expressions"
.
DelphiTools
. Retrieved
11 September
2025
.
^
"Coming in RAD Studio 13: A Conditional Ternary Operator for the Delphi Language"
.
Embarcadero Blogs
. 30 July 2025
. Retrieved
11 September
2025
.
^
"Texas, Start Your Photocopiers"
.
RemObjects Blog
. Retrieved
11 September
2025
.
^
"The Python Language Reference"
.
^
"Remove Ternary Operator by pwoolcoc · Pull Request #1705 · rust-lang/Rust"
.
GitHub
.
^
"Remove ternary operator · Issue #1698 · rust-lang/Rust"
.
GitHub
.
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 |
| Markdown | [Jump to content](https://en.wikipedia.org/wiki/Ternary_conditional_operator#bodyContent)
Main menu
Main menu
move to sidebar
hide
Navigation
- [Main page](https://en.wikipedia.org/wiki/Main_Page "Visit the main page [z]")
- [Contents](https://en.wikipedia.org/wiki/Wikipedia:Contents "Guides to browsing Wikipedia")
- [Current events](https://en.wikipedia.org/wiki/Portal:Current_events "Articles related to current events")
- [Random article](https://en.wikipedia.org/wiki/Special:Random "Visit a randomly selected article [x]")
- [About Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:About "Learn about Wikipedia and how it works")
- [Contact us](https://en.wikipedia.org/wiki/Wikipedia:Contact_us "How to contact Wikipedia")
Contribute
- [Help](https://en.wikipedia.org/wiki/Help:Contents "Guidance on how to use and edit Wikipedia")
- [Learn to edit](https://en.wikipedia.org/wiki/Help:Introduction "Learn how to edit Wikipedia")
- [Community portal](https://en.wikipedia.org/wiki/Wikipedia:Community_portal "The hub for editors")
- [Recent changes](https://en.wikipedia.org/wiki/Special:RecentChanges "A list of recent changes to Wikipedia [r]")
- [Upload file](https://en.wikipedia.org/wiki/Wikipedia:File_upload_wizard "Add images or other media for use on Wikipedia")
- [Special pages](https://en.wikipedia.org/wiki/Special:SpecialPages "A list of all special pages [q]")
[  ](https://en.wikipedia.org/wiki/Main_Page)
[Search](https://en.wikipedia.org/wiki/Special:Search "Search Wikipedia [f]")
Appearance
- [Donate](https://donate.wikimedia.org/?wmf_source=donate&wmf_medium=sidebar&wmf_campaign=en.wikipedia.org&uselang=en)
- [Create account](https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Ternary+conditional+operator "You are encouraged to create an account and log in; however, it is not mandatory")
- [Log in](https://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Ternary+conditional+operator "You're encouraged to log in; however, it's not mandatory. [o]")
Personal tools
- [Donate](https://donate.wikimedia.org/?wmf_source=donate&wmf_medium=sidebar&wmf_campaign=en.wikipedia.org&uselang=en)
- [Create account](https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Ternary+conditional+operator "You are encouraged to create an account and log in; however, it is not mandatory")
- [Log in](https://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Ternary+conditional+operator "You're encouraged to log in; however, it's not mandatory. [o]")
## Contents
move to sidebar
hide
- [(Top)](https://en.wikipedia.org/wiki/Ternary_conditional_operator)
- [1 Patterns](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Patterns)
Toggle Patterns subsection
- [1\.1 Assignment](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Assignment)
- [1\.2 Case selector](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Case_selector)
- [2 Variations](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Variations)
- [3 Equivalence to map](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Equivalence_to_map)
- [4 Examples](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Examples)
Toggle Examples subsection
- [4\.1 Ada](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Ada)
- [4\.2 ALGOL 60](https://en.wikipedia.org/wiki/Ternary_conditional_operator#ALGOL_60)
- [4\.3 ALGOL 68](https://en.wikipedia.org/wiki/Ternary_conditional_operator#ALGOL_68)
- [4\.4 Bash](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Bash)
- [4\.5 C family](https://en.wikipedia.org/wiki/Ternary_conditional_operator#C_family)
- [4\.6 Common Lisp](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Common_Lisp)
- [4\.7 dBASE](https://en.wikipedia.org/wiki/Ternary_conditional_operator#dBASE)
- [4\.8 Fortran](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Fortran)
- [4\.9 Kotlin](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Kotlin)
- [4\.10 Lua](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Lua)
- [4\.11 Pascal](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Pascal)
- [4\.12 Python](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Python)
- [4\.13 Rust](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Rust)
- [4\.14 Smalltalk](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Smalltalk)
- [4\.15 SQL](https://en.wikipedia.org/wiki/Ternary_conditional_operator#SQL)
- [4\.16 Visual Basic](https://en.wikipedia.org/wiki/Ternary_conditional_operator#Visual_Basic)
- [5 See also](https://en.wikipedia.org/wiki/Ternary_conditional_operator#See_also)
- [6 References](https://en.wikipedia.org/wiki/Ternary_conditional_operator#References)
- [7 External links](https://en.wikipedia.org/wiki/Ternary_conditional_operator#External_links)
Toggle the table of contents
# Ternary conditional operator
12 languages
- [Čeština](https://cs.wikipedia.org/wiki/Tern%C3%A1rn%C3%AD_oper%C3%A1tor_\(programov%C3%A1n%C3%AD\) "Ternární operátor (programování) – Czech")
- [Deutsch](https://de.wikipedia.org/wiki/Bedingte_Anweisung_und_Verzweigung#Auswahloperator "Bedingte Anweisung und Verzweigung – German")
- [Français](https://fr.wikipedia.org/wiki/Op%C3%A9rateur_conditionnel_ternaire "Opérateur conditionnel ternaire – French")
- [Italiano](https://it.wikipedia.org/wiki/%3F: "?: – Italian")
- [日本語](https://ja.wikipedia.org/wiki/%E6%9D%A1%E4%BB%B6%E6%BC%94%E7%AE%97%E5%AD%90 "条件演算子 – Japanese")
- [한국어](https://ko.wikipedia.org/wiki/%3F: "?: – Korean")
- [Polski](https://pl.wikipedia.org/wiki/Operator_warunkowy "Operator warunkowy – Polish")
- [Português](https://pt.wikipedia.org/wiki/%3F: "?: – Portuguese")
- [Русский](https://ru.wikipedia.org/wiki/%D0%A2%D0%B5%D1%80%D0%BD%D0%B0%D1%80%D0%BD%D0%B0%D1%8F_%D1%83%D1%81%D0%BB%D0%BE%D0%B2%D0%BD%D0%B0%D1%8F_%D0%BE%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F "Тернарная условная операция – Russian")
- [Türkçe](https://tr.wikipedia.org/wiki/%3F: "?: – Turkish")
- [Українська](https://uk.wikipedia.org/wiki/%D0%A2%D0%B5%D1%80%D0%BD%D0%B0%D1%80%D0%BD%D0%B0_%D1%83%D0%BC%D0%BE%D0%B2%D0%BD%D0%B0_%D0%BE%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D1%96%D1%8F "Тернарна умовна операція – Ukrainian")
- [中文](https://zh.wikipedia.org/wiki/%E6%9D%A1%E4%BB%B6%E8%BF%90%E7%AE%97%E7%AC%A6%3F: "条件运算符?: – Chinese")
[Edit links](https://www.wikidata.org/wiki/Special:EntityPage/Q2984985#sitelinks-wikipedia "Edit interlanguage links")
- [Article](https://en.wikipedia.org/wiki/Ternary_conditional_operator "View the content page [c]")
- [Talk](https://en.wikipedia.org/wiki/Talk:Ternary_conditional_operator "Discuss improvements to the content page [t]")
English
- [Read](https://en.wikipedia.org/wiki/Ternary_conditional_operator)
- [Edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit "Edit this page [e]")
- [View history](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=history "Past revisions of this page [h]")
Tools
Tools
move to sidebar
hide
Actions
- [Read](https://en.wikipedia.org/wiki/Ternary_conditional_operator)
- [Edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit "Edit this page [e]")
- [View history](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=history)
General
- [What links here](https://en.wikipedia.org/wiki/Special:WhatLinksHere/Ternary_conditional_operator "List of all English Wikipedia pages containing links to this page [j]")
- [Related changes](https://en.wikipedia.org/wiki/Special:RecentChangesLinked/Ternary_conditional_operator "Recent changes in pages linked from this page [k]")
- [Upload file](https://en.wikipedia.org/wiki/Wikipedia:File_Upload_Wizard "Upload files [u]")
- [Permanent link](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&oldid=1341687706 "Permanent link to this revision of this page")
- [Page information](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=info "More information about this page")
- [Cite this page](https://en.wikipedia.org/w/index.php?title=Special:CiteThisPage&page=Ternary_conditional_operator&id=1341687706&wpFormIdentifier=titleform "Information on how to cite this page")
- [Get shortened URL](https://en.wikipedia.org/w/index.php?title=Special:UrlShortener&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FTernary_conditional_operator)
Print/export
- [Download as PDF](https://en.wikipedia.org/w/index.php?title=Special:DownloadAsPdf&page=Ternary_conditional_operator&action=show-download-screen "Download this page as a PDF file")
- [Printable version](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&printable=yes "Printable version of this page [p]")
In other projects
- [Wikidata item](https://www.wikidata.org/wiki/Special:EntityPage/Q2984985 "Structured data on this page hosted by Wikidata [g]")
Appearance
move to sidebar
hide
From Wikipedia, the free encyclopedia
Conditional operator in computer programming
"?:" redirects here. For use as a binary operator, see [Elvis operator](https://en.wikipedia.org/wiki/Elvis_operator "Elvis operator").
"Conditional operator" redirects here. For the `||` and `&&` operators, sometimes called conditional operators in Java and C\#, see [Short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation "Short-circuit evaluation").
In [computer programming](https://en.wikipedia.org/wiki/Computer_programming "Computer programming"), the **ternary conditional operator** is a [ternary operator](https://en.wikipedia.org/wiki/Ternary_operator "Ternary operator") that evaluates to one of two values based on a [Boolean expression](https://en.wikipedia.org/wiki/Boolean_expression "Boolean expression"). The operator is also known as **conditional operator**, **ternary if**, **immediate if**, or **inline if** (**iif**). 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](https://en.wikipedia.org/wiki/Expression_\(computer_science\) "Expression (computer science)") using the operator is like `if a then b else c` or `a ? b : c`. One can read it aloud as "if a then b otherwise c". The form `a ? b : c` is the most common, but alternative syntax exists. For example, [Raku](https://en.wikipedia.org/wiki/Raku_\(programming_language\) "Raku (programming language)") uses the syntax `a ?? b !! c` to avoid confusion with the infix operators `?` and `!`, whereas in [Visual Basic](https://en.wikipedia.org/wiki/Visual_Basic "Visual Basic"), it takes the form `If(a, b, c)`.
The construct first appeared in [CPL](https://en.wikipedia.org/wiki/CPL_\(programming_language\) "CPL (programming language)"), in which equivalent syntax for `a ? b : c` is `a → b, c`.[\[1\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-1)[\[2\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-2)
## Patterns
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=1 "Edit section: Patterns")\]
### Assignment
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=2 "Edit section: Assignment")\]
The value of the operator can be assigned to a variable. For a weakly typed language, the [data type](https://en.wikipedia.org/wiki/Data_type "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 (if-then-else) work in [functional programming](https://en.wikipedia.org/wiki/Functional_programming "Functional programming") languages, like [Scheme](https://en.wikipedia.org/wiki/Scheme_\(programming_language\) "Scheme (programming language)"), [ML](https://en.wikipedia.org/wiki/ML_\(programming_language\) "ML (programming language)"), [Haskell](https://en.wikipedia.org/wiki/Haskell "Haskell"), and [XQuery](https://en.wikipedia.org/wiki/XQuery "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](https://en.wikipedia.org/wiki/Block_scope "Block scope"), a variable must be declared before the if-else statement. For example:
```
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. For example:
```
const std::string s = b ? "foo" : "bar";
```
### Case selector
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=3 "Edit section: 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
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=4 "Edit section: Variations")\]
The syntax and semantics of the operator vary by language.
Major differences include whether the expressions can have [side effects](https://en.wikipedia.org/wiki/Side_effect_\(computer_science\) "Side effect (computer science)") and whether the language provides [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation "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 (the value obtained from *some* order) or [undefined](https://en.wikipedia.org/wiki/Undefined_behavior "Undefined behavior") (any value at all at the whim of the compiler in the face of side effects, or even a crash).
If a 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 `r = condition ? expr1 : expr2` can have subtly different semantics than the block conditional form `if (condition) { r = expr1; } else { r = expr2; }`.
In almost all languages, the ternary operator is [right associative](https://en.wikipedia.org/wiki/Right_associative "Right associative"), so that `a == 1 ? "one" : a == 2 ? "two" : "many"` evaluates intuitively as `a == 1 ? "one" : (a == 2 ? "two" : "many")`. This means it can be chained similarly to an `if ... else if ... else if ... else` chain. The main exception is [PHP](https://en.wikipedia.org/wiki/PHP "PHP"), in which it was left-associative (such that the same expression evaluates to `(a == 1 ? "one" : a == 2) ? "two" : "many"`, which is rarely what the programmer expects)[\[3\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-3) prior to version 8, and is non-associative thereafter.[\[4\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-4)
Furthermore, in all C-family languages and many others, the ternary conditional operator has low [operator precedence](https://en.wikipedia.org/wiki/Order_of_operations "Order of operations").
## Equivalence to map
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=5 "Edit section: 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 `c(expr1,expr2)[1+condition]` (this idiom is slightly more natural in languages with 0-origin subscripts). Nested ternaries can be simulated as `c(expr1,expr2,expr3)[which.first((c(cond1,cond2,TRUE))]` where the function `which.first` 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](https://en.wikipedia.org/wiki/Currying "Currying") based on data concatenation rather than function composition.
If the language provides a mechanism of [futures or promises](https://en.wikipedia.org/wiki/Futures_and_promises "Futures and promises"), then short-circuit evaluation can sometimes also be simulated in the context of a binary map operation.
## Examples
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=6 "Edit section: Examples")\]
### Ada
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=7 "Edit section: Ada")\]
The 2012 edition of [Ada](https://en.wikipedia.org/wiki/Ada_\(programming_language\) "Ada (programming language)") has introduced conditional expressions (using `if` and `case`), as part of an enlarged set of expressions including quantified expressions and expression functions. The Rationale for Ada 2012[\[5\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-5) 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 `else` part may be omitted, the value being True. Multiple conditions may chained using `elsif`.
### ALGOL 60
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=8 "Edit section: ALGOL 60")\]
ALGOL 60 introduced [conditional expressions](https://en.wikipedia.org/wiki/ALGOL_60#Expressions_and_compound_statements "ALGOL 60") (ternary conditionals) to [imperative programming](https://en.wikipedia.org/wiki/Imperative_programming "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
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=9 "Edit section: ALGOL 68")\]
Both [ALGOL 68](https://en.wikipedia.org/wiki/ALGOL_68 "ALGOL 68")'s [choice clauses](https://en.wikipedia.org/wiki/ALGOL_68#Expressions_and_compound_statements "ALGOL 68") (if and case clauses) support the following:
Single if choice clause
`if condition then statements [ else statements ] fi` or a brief form: `( condition | statements | statements )`
Chained if choice clause
`if condition1 then statements elif condition2 then statements [ else statements ] fi` or a brief form: `( condition1 | statements |: condition2 | statements | statements )`.
### Bash
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=10 "Edit section: Bash")\]
A true ternary operator exists for arithmetic expressions:
```
((result = condition ? value_if_true : value_if_false))
```
For strings there are workarounds, like e.g.:
```
result=$(if condition ; then echo "value_if_true" ; else echo "value_if_false" ; fi)
```
Where `condition` can be any bash command. When it exits with success, the first echo command is executed, otherwise the second one is executed.
### C family
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=11 "Edit section: C family")\]
The following code in [C](https://en.wikipedia.org/wiki/C_\(programming_language\) "C (programming language)") assigns `result` to the value of `x` if `a > b`, and otherwise to the value of `y`. This is the same syntax as in many related languages including [C++](https://en.wikipedia.org/wiki/C%2B%2B "C++"), [Java](https://en.wikipedia.org/wiki/Java_\(programming_language\) "Java (programming language)"), [JavaScript](https://en.wikipedia.org/wiki/JavaScript "JavaScript"), and [Dart](https://en.wikipedia.org/wiki/Dart_\(programming_language\) "Dart (programming language)").
```
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](https://en.wikipedia.org/wiki/Side_effect_\(computer_science\) "Side effect (computer science)"). Only the side-effect for the selected expression value will occur.[\[6\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-ISO/IEC_9899:1999-6)[\[7\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-java-7)
If `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 `x` and `y` to 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.[\[8\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-8)
- In C\#, if one expression is implicitly convertible to the type of the other, that type is used. Otherwise, a compile-time error occurs.[\[9\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-:0-9)
- In dynamically typed languages, the evaluated expression has the type of the selected expression.
Furthermore, in C++, a conditional expression can be used as an [lvalue](https://en.wikipedia.org/wiki/Value_\(computer_science\)#lrvalue "Value (computer science)"), if both `x` and `y` are lvalues, though this is rarely used in practice:[\[10\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-10)
```
(foo ? bar : baz) = frink;
```
### Common Lisp
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=12 "Edit section: Common Lisp")\]
Assignment using a conditional expression in [Common Lisp](https://en.wikipedia.org/wiki/Common_Lisp "Common Lisp"):
```
(setq result (if (> a b) x y))
```
Alternative form:
```
(if (> a b)
(setq result x)
(setq result y))
```
### dBASE
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=13 "Edit section: dBASE")\]
In [dBase](https://en.wikipedia.org/wiki/DBase "DBase"), the conditional function `iif(<expL>, <expT>, <expF>)` is called "Immediate IF". It uses shortcut evaluation (it only evaluates one of `<expT>` or `<expF>`).
For example, to sort a list by the street name and then (in most cases) house number, one could type
```
index on iif(instr(addr," ") , substr(addr,instr(addr," ")+1,10) + left(addr,instr(addr," ")-1) , addr) to indexfile
```
at the dBASE III command prompt, and then copy or export the table.
### Fortran
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=14 "Edit section: Fortran")\]
As part of the Fortran-90 Standard, the ternary operator was added to [Fortran](https://en.wikipedia.org/wiki/Fortran "Fortran") as the intrinsic function `merge`:
```
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.
Fortran-2023 added conditional expressions which evaluate one or the other of the expressions based on the conditional expression:
```
variable = ( a > b ? x : y )
```
### Kotlin
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=15 "Edit section: Kotlin")\]
Kotlin does not include the traditional `?:` ternary operator, however, an `if` can be used as an expression that can be assigned,[\[11\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-11) achieving the same results.
```
val max = if (a > b) a else b
```
### Lua
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=16 "Edit section: Lua")\]
Lua does not have a traditional conditional operator. However, the short-circuiting behavior of its `and` and `or` 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 `a` is logically false; in this case, the expression will always result in `b`. 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 = (
{
[true] = a,
[false] = b
}
)[not not cond]
```
Luau, a dialect of Lua, has ternary expressions that look like if statements, but unlike them, they have no `end` keyword, and the `else` clause is required. One may optionally add `elseif` clauses. It's designed to replace the `cond and a or b` idiom and is expected to work properly in all cases.[\[12\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-12)
```
-- 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
```
### Pascal
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=17 "Edit section: Pascal")\]
Pascal was both a simplification and extension of ALGOL 60 (mainly for handling user-defined types). One simplification was to remove the conditional expression since the same could be achieved with the less succinct conditional statement form.
[RemObjects Oxygene](https://en.wikipedia.org/wiki/RemObjects_Elements "RemObjects Elements") added a ternary operator to Object Pascal in approximately 2011,[\[13\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-13) and in 2025 Delphi followed suit.[\[14\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-14) Oxygene supports [case/switch statements](https://en.wikipedia.org/wiki/Switch_statement "Switch statement"), essentially a repeated if, as expressions evaluating to a value as well.[\[15\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-15)
### Python
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=18 "Edit section: Python")\]
An operator for a conditional expression in [Python](https://en.wikipedia.org/wiki/Python_\(programming_language\) "Python (programming language)") was approved as [Python Enhancement Proposal 308](https://peps.python.org/pep-0308/) 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:[\[16\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-16)
```
result = x if a > b else y
```
This form invites considering `x` as the normal value and `y` as an exceptional case.
### Rust
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=19 "Edit section: Rust")\]
Being an [expression-oriented programming language](https://en.wikipedia.org/wiki/Expression-oriented_programming_language "Expression-oriented programming language"), 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[\[17\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-17) due to duplication with `if`.[\[18\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-18)
Note the lack of semi-colons in the code below compared to a more declarative `if`...`else` block, and the semi-colon at the end of the assignment to `y`.
```
let x = 5;
let y = if x == 5 {
10
} else {
15
};
```
This could also be written as:
```
let y = if x == 5 { 10 } else { 15 };
```
Note that curly braces are mandatory in Rust conditional expressions.
You could also use a `match` expression:
```
let y = match x {
5 => 10,
_ => 15,
};
```
### Smalltalk
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=20 "Edit section: Smalltalk")\]
Every expression (message send) has a value. Thus `ifTrue:ifFalse:` can be used:
```
|x y|
x := 5.
y := (x == 5) ifTrue:[10] ifFalse:[15].
```
### SQL
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=21 "Edit section: SQL")\]
The SQL `CASE` 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;
```
### Visual Basic
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=22 "Edit section: Visual Basic")\]
[Visual Basic](https://en.wikipedia.org/wiki/Visual_Basic "Visual Basic") provides a ternary conditional function, `IIf`, as shown in the following code:
```
Dim opening_time As Integer = IIf((day = SUNDAY), 12, 9)
```
As a function, the values of the three arguments are evaluated before the function is called. To avoid evaluating the expression that is not selected, the `If` keyword was added (in Visual Basic .Net 9.0) as a true ternary conditional operator. This allows the following code to avoid an exception if it were implemented with `IIf` instead:
```
Dim name As String = If(person Is Nothing, "", person.Name)
```
## See also
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=23 "Edit section: See also")\]
- [Conditioned disjunction](https://en.wikipedia.org/wiki/Conditioned_disjunction "Conditioned disjunction")
- [Elvis operator](https://en.wikipedia.org/wiki/Elvis_operator "Elvis operator") – Binary operator in computer programming
- [McCarthy Formalism](https://en.wikipedia.org/wiki/McCarthy_Formalism "McCarthy Formalism") – Computer science and recursion theory
- [Multiplexer](https://en.wikipedia.org/wiki/Multiplexer "Multiplexer") – Device that selects between several analog or digital input signals
- [Null coalescing operator](https://en.wikipedia.org/wiki/Null_coalescing_operator "Null coalescing operator") – Binary operator in computer programming
- [Safe navigation operator](https://en.wikipedia.org/wiki/Safe_navigation_operator "Safe navigation operator") – Boolean operator
- [Three-way comparison](https://en.wikipedia.org/wiki/Three-way_comparison "Three-way comparison") (one numeric expression selects one of three statements or branches)
## References
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=24 "Edit section: References")\]
1. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-1)**
[Strachey, Christopher](https://en.wikipedia.org/wiki/Christopher_Strachey "Christopher Strachey") (2000). "[Fundamental Concepts in Programming Languages](https://en.wikipedia.org/wiki/Fundamental_Concepts_in_Programming_Languages "Fundamental Concepts in Programming Languages")". *[Higher-Order and Symbolic Computation](https://en.wikipedia.org/wiki/Higher-Order_and_Symbolic_Computation "Higher-Order and Symbolic Computation")*. **13** (1–2\): 11–49\. [doi](https://en.wikipedia.org/wiki/Doi_\(identifier\) "Doi (identifier)"):[10\.1023/A:1010000313106](https://doi.org/10.1023%2FA%3A1010000313106). [S2CID](https://en.wikipedia.org/wiki/S2CID_\(identifier\) "S2CID (identifier)") [14124601](https://api.semanticscholar.org/CorpusID:14124601).
2. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-2)**
"5.5 Conditional expressions". [*The BCPL Reference Manual*](https://web.archive.org/web/20160316100234/http://www.eah-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf) (PDF). 1967. pp. 16–17\. Archived from [the original](http://www.eah-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf) (PDF) on 2016-03-16. Retrieved 2017-03-15.
3. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-3)**
Wastl, Eric. ["Ternary operator associativity"](http://phpsadness.com/sad/30). *phpsadness.com*. PHP Sadness. Retrieved 20 September 2017.
4. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-4)** <https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary>
5. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-5)**
["Rationale for Ada 2012"](http://www.ada-auth.org/standards/12rat/html/Rat12-2-1.html). ACAA. Retrieved 10 December 2015.
6. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-ISO/IEC_9899:1999_6-0)** ISO.IEC 9899:1999 (E) 6.5.15.4
7. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-java_7-0)** Java 7 Specification: [15\.25 Conditional Operator ? :](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25)
8. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-8)**
mikeblome. ["Conditional Operator: ?"](https://docs.microsoft.com/en-us/cpp/cpp/conditional-operator-q). *docs.microsoft.com*. Retrieved 2019-04-29.
9. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-:0_9-0)**
BillWagner. ["?: Operator - C\# Reference"](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator). *docs.microsoft.com*. Retrieved 2019-04-29.
10. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-10)**
["Conditional Operator"](http://wiki.c2.com/?ConditionalOperator). *wiki.c2.com*. Retrieved 2019-04-29.
11. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-11)**
["Kotlin Lang If Expression"](https://kotlinlang.org/docs/control-flow.html#if-expression). *kotlinlang.org*. Retrieved 2021-04-25.
12. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-12)**
["Syntax § If-then-else expressions"](https://luau.org/syntax#if-then-else-expressions). *Luau*. Retrieved 2023-02-07.
13. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-13)**
["if then (else) expressions"](https://www.delphitools.info/2013/01/08/if-then-else-expressions/). *DelphiTools*. Retrieved 11 September 2025.
14. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-14)**
["Coming in RAD Studio 13: A Conditional Ternary Operator for the Delphi Language"](https://blogs.embarcadero.com/coming-in-rad-studio-13-a-conditional-ternary-operator-for-the-delphi-language/). *Embarcadero Blogs*. 30 July 2025. Retrieved 11 September 2025.
15. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-15)**
["Texas, Start Your Photocopiers"](https://blogs.remobjects.com/2025/09/10/texas-start-your-photocopiers/). *RemObjects Blog*. Retrieved 11 September 2025.
16. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-16)**
["The Python Language Reference"](https://docs.python.org/3/reference/expressions.html#conditional-expressions).
17. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-17)**
["Remove Ternary Operator by pwoolcoc · Pull Request \#1705 · rust-lang/Rust"](https://github.com/rust-lang/rust/pull/1705). *[GitHub](https://en.wikipedia.org/wiki/GitHub "GitHub")*.
18. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-18)**
["Remove ternary operator · Issue \#1698 · rust-lang/Rust"](https://github.com/rust-lang/rust/issues/1698). *[GitHub](https://en.wikipedia.org/wiki/GitHub "GitHub")*.
## External links
\[[edit](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&action=edit§ion=25 "Edit section: External links")\]
- [Description of If operator in Visual Basic](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator)
- [Description of Conditional Expression in Python (PEP 308)](https://peps.python.org/pep-0308/)
- [Description in the Java Language Specification](https://docs.oracle.com/javase/specs/#15.25)
- [Description in the PHP Language Documentation](https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary)

Retrieved from "<https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&oldid=1341687706>"
[Categories](https://en.wikipedia.org/wiki/Help:Category "Help:Category"):
- [Conditional constructs](https://en.wikipedia.org/wiki/Category:Conditional_constructs "Category:Conditional constructs")
- [Operators (programming)](https://en.wikipedia.org/wiki/Category:Operators_\(programming\) "Category:Operators (programming)")
- [Ternary operations](https://en.wikipedia.org/wiki/Category:Ternary_operations "Category:Ternary operations")
Hidden categories:
- [Articles with short description](https://en.wikipedia.org/wiki/Category:Articles_with_short_description "Category:Articles with short description")
- [Short description is different from Wikidata](https://en.wikipedia.org/wiki/Category:Short_description_is_different_from_Wikidata "Category:Short description is different from Wikidata")
- [Articles with example code](https://en.wikipedia.org/wiki/Category:Articles_with_example_code "Category:Articles with example code")
- This page was last edited on 4 March 2026, at 13:54 (UTC).
- Text is available under the [Creative Commons Attribution-ShareAlike 4.0 License](https://en.wikipedia.org/wiki/Wikipedia:Text_of_the_Creative_Commons_Attribution-ShareAlike_4.0_International_License "Wikipedia:Text of the Creative Commons Attribution-ShareAlike 4.0 International License"); additional terms may apply. By using this site, you agree to the [Terms of Use](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Terms_of_Use "foundation:Special:MyLanguage/Policy:Terms of Use") and [Privacy Policy](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy "foundation:Special:MyLanguage/Policy:Privacy policy"). Wikipedia® is a registered trademark of the [Wikimedia Foundation, Inc.](https://wikimediafoundation.org/), a non-profit organization.
- [Privacy policy](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy)
- [About Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:About)
- [Disclaimers](https://en.wikipedia.org/wiki/Wikipedia:General_disclaimer)
- [Contact Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:Contact_us)
- [Legal & safety contacts](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Legal:Wikimedia_Foundation_Legal_and_Safety_Contact_Information)
- [Code of Conduct](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Universal_Code_of_Conduct)
- [Developers](https://developer.wikimedia.org/)
- [Statistics](https://stats.wikimedia.org/#/en.wikipedia.org)
- [Cookie statement](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Cookie_statement)
- [Mobile view](https://en.wikipedia.org/w/index.php?title=Ternary_conditional_operator&mobileaction=toggle_view_mobile)
- [](https://www.wikimedia.org/)
- [](https://www.mediawiki.org/)
Search
Toggle the table of contents
Ternary conditional operator
12 languages
[Add topic](https://en.wikipedia.org/wiki/Ternary_conditional_operator) |
| Readable Markdown | "?:" redirects here. For use as a binary operator, see [Elvis operator](https://en.wikipedia.org/wiki/Elvis_operator "Elvis operator").
"Conditional operator" redirects here. For the `||` and `&&` operators, sometimes called conditional operators in Java and C\#, see [Short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation "Short-circuit evaluation").
In [computer programming](https://en.wikipedia.org/wiki/Computer_programming "Computer programming"), the **ternary conditional operator** is a [ternary operator](https://en.wikipedia.org/wiki/Ternary_operator "Ternary operator") that evaluates to one of two values based on a [Boolean expression](https://en.wikipedia.org/wiki/Boolean_expression "Boolean expression"). The operator is also known as **conditional operator**, **ternary if**, **immediate if**, or **inline if** (**iif**). 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](https://en.wikipedia.org/wiki/Expression_\(computer_science\) "Expression (computer science)") using the operator is like `if a then b else c` or `a ? b : c`. One can read it aloud as "if a then b otherwise c". The form `a ? b : c` is the most common, but alternative syntax exists. For example, [Raku](https://en.wikipedia.org/wiki/Raku_\(programming_language\) "Raku (programming language)") uses the syntax `a ?? b !! c` to avoid confusion with the infix operators `?` and `!`, whereas in [Visual Basic](https://en.wikipedia.org/wiki/Visual_Basic "Visual Basic"), it takes the form `If(a, b, c)`.
The construct first appeared in [CPL](https://en.wikipedia.org/wiki/CPL_\(programming_language\) "CPL (programming language)"), in which equivalent syntax for `a ? b : c` is `a → b, c`.[\[1\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-1)[\[2\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-2)
The value of the operator can be assigned to a variable. For a weakly typed language, the [data type](https://en.wikipedia.org/wiki/Data_type "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 (if-then-else) work in [functional programming](https://en.wikipedia.org/wiki/Functional_programming "Functional programming") languages, like [Scheme](https://en.wikipedia.org/wiki/Scheme_\(programming_language\) "Scheme (programming language)"), [ML](https://en.wikipedia.org/wiki/ML_\(programming_language\) "ML (programming language)"), [Haskell](https://en.wikipedia.org/wiki/Haskell "Haskell"), and [XQuery](https://en.wikipedia.org/wiki/XQuery "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](https://en.wikipedia.org/wiki/Block_scope "Block scope"), a variable must be declared before the if-else statement. For example:
```
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. For example:
```
const std::string s = b ? "foo" : "bar";
```
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;
```
The syntax and semantics of the operator vary by language.
Major differences include whether the expressions can have [side effects](https://en.wikipedia.org/wiki/Side_effect_\(computer_science\) "Side effect (computer science)") and whether the language provides [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation "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 (the value obtained from *some* order) or [undefined](https://en.wikipedia.org/wiki/Undefined_behavior "Undefined behavior") (any value at all at the whim of the compiler in the face of side effects, or even a crash).
If a 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 `r = condition ? expr1 : expr2` can have subtly different semantics than the block conditional form `if (condition) { r = expr1; } else { r = expr2; }`.
In almost all languages, the ternary operator is [right associative](https://en.wikipedia.org/wiki/Right_associative "Right associative"), so that `a == 1 ? "one" : a == 2 ? "two" : "many"` evaluates intuitively as `a == 1 ? "one" : (a == 2 ? "two" : "many")`. This means it can be chained similarly to an `if ... else if ... else if ... else` chain. The main exception is [PHP](https://en.wikipedia.org/wiki/PHP "PHP"), in which it was left-associative (such that the same expression evaluates to `(a == 1 ? "one" : a == 2) ? "two" : "many"`, which is rarely what the programmer expects)[\[3\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-3) prior to version 8, and is non-associative thereafter.[\[4\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-4)
Furthermore, in all C-family languages and many others, the ternary conditional operator has low [operator precedence](https://en.wikipedia.org/wiki/Order_of_operations "Order of operations").
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 `c(expr1,expr2)[1+condition]` (this idiom is slightly more natural in languages with 0-origin subscripts). Nested ternaries can be simulated as `c(expr1,expr2,expr3)[which.first((c(cond1,cond2,TRUE))]` where the function `which.first` 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](https://en.wikipedia.org/wiki/Currying "Currying") based on data concatenation rather than function composition.
If the language provides a mechanism of [futures or promises](https://en.wikipedia.org/wiki/Futures_and_promises "Futures and promises"), then short-circuit evaluation can sometimes also be simulated in the context of a binary map operation.
The 2012 edition of [Ada](https://en.wikipedia.org/wiki/Ada_\(programming_language\) "Ada (programming language)") has introduced conditional expressions (using `if` and `case`), as part of an enlarged set of expressions including quantified expressions and expression functions. The Rationale for Ada 2012[\[5\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-5) 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 `else` part may be omitted, the value being True. Multiple conditions may chained using `elsif`.
ALGOL 60 introduced [conditional expressions](https://en.wikipedia.org/wiki/ALGOL_60#Expressions_and_compound_statements "ALGOL 60") (ternary conditionals) to [imperative programming](https://en.wikipedia.org/wiki/Imperative_programming "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;
```
Both [ALGOL 68](https://en.wikipedia.org/wiki/ALGOL_68 "ALGOL 68")'s [choice clauses](https://en.wikipedia.org/wiki/ALGOL_68#Expressions_and_compound_statements "ALGOL 68") (if and case clauses) support the following:
Single if choice clause
`if condition then statements [ else statements ] fi` or a brief form: `( condition | statements | statements )`
Chained if choice clause
`if condition1 then statements elif condition2 then statements [ else statements ] fi` or a brief form: `( condition1 | statements |: condition2 | statements | statements )`.
A true ternary operator exists for arithmetic expressions:
```
((result = condition ? value_if_true : value_if_false))
```
For strings there are workarounds, like e.g.:
```
result=$(if condition ; then echo "value_if_true" ; else echo "value_if_false" ; fi)
```
Where `condition` can be any bash command. When it exits with success, the first echo command is executed, otherwise the second one is executed.
The following code in [C](https://en.wikipedia.org/wiki/C_\(programming_language\) "C (programming language)") assigns `result` to the value of `x` if `a > b`, and otherwise to the value of `y`. This is the same syntax as in many related languages including [C++](https://en.wikipedia.org/wiki/C%2B%2B "C++"), [Java](https://en.wikipedia.org/wiki/Java_\(programming_language\) "Java (programming language)"), [JavaScript](https://en.wikipedia.org/wiki/JavaScript "JavaScript"), and [Dart](https://en.wikipedia.org/wiki/Dart_\(programming_language\) "Dart (programming language)").
```
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](https://en.wikipedia.org/wiki/Side_effect_\(computer_science\) "Side effect (computer science)"). Only the side-effect for the selected expression value will occur.[\[6\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-ISO/IEC_9899:1999-6)[\[7\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-java-7)
If `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 `x` and `y` to 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.[\[8\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-8)
- In C\#, if one expression is implicitly convertible to the type of the other, that type is used. Otherwise, a compile-time error occurs.[\[9\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-:0-9)
- In dynamically typed languages, the evaluated expression has the type of the selected expression.
Furthermore, in C++, a conditional expression can be used as an [lvalue](https://en.wikipedia.org/wiki/Value_\(computer_science\)#lrvalue "Value (computer science)"), if both `x` and `y` are lvalues, though this is rarely used in practice:[\[10\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-10)
```
(foo ? bar : baz) = frink;
```
Assignment using a conditional expression in [Common Lisp](https://en.wikipedia.org/wiki/Common_Lisp "Common Lisp"):
```
(setq result (if (> a b) x y))
```
Alternative form:
```
(if (> a b)
(setq result x)
(setq result y))
```
In [dBase](https://en.wikipedia.org/wiki/DBase "DBase"), the conditional function `iif(<expL>, <expT>, <expF>)` is called "Immediate IF". It uses shortcut evaluation (it only evaluates one of \<expT\> or \<expF\>).
For example, to sort a list by the street name and then (in most cases) house number, one could type
```
index on iif(instr(addr," ") , substr(addr,instr(addr," ")+1,10) + left(addr,instr(addr," ")-1) , addr) to indexfile
```
at the dBASE III command prompt, and then copy or export the table.
As part of the Fortran-90 Standard, the ternary operator was added to [Fortran](https://en.wikipedia.org/wiki/Fortran "Fortran") as the intrinsic function `merge`:
```
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.
Fortran-2023 added conditional expressions which evaluate one or the other of the expressions based on the conditional expression:
```
variable = ( a > b ? x : y )
```
Kotlin does not include the traditional `?:` ternary operator, however, an `if` can be used as an expression that can be assigned,[\[11\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-11) achieving the same results.
```
val max = if (a > b) a else b
```
Lua does not have a traditional conditional operator. However, the short-circuiting behavior of its `and` and `or` 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 `a` is logically false; in this case, the expression will always result in `b`. 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 = (
{
[true] = a,
[false] = b
}
)[not not cond]
```
Luau, a dialect of Lua, has ternary expressions that look like if statements, but unlike them, they have no `end` keyword, and the `else` clause is required. One may optionally add `elseif` clauses. It's designed to replace the `cond and a or b` idiom and is expected to work properly in all cases.[\[12\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-12)
```
-- 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
```
Pascal was both a simplification and extension of ALGOL 60 (mainly for handling user-defined types). One simplification was to remove the conditional expression since the same could be achieved with the less succinct conditional statement form.
[RemObjects Oxygene](https://en.wikipedia.org/wiki/RemObjects_Elements "RemObjects Elements") added a ternary operator to Object Pascal in approximately 2011,[\[13\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-13) and in 2025 Delphi followed suit.[\[14\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-14) Oxygene supports [case/switch statements](https://en.wikipedia.org/wiki/Switch_statement "Switch statement"), essentially a repeated if, as expressions evaluating to a value as well.[\[15\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-15)
An operator for a conditional expression in [Python](https://en.wikipedia.org/wiki/Python_\(programming_language\) "Python (programming language)") was approved as [Python Enhancement Proposal 308](https://peps.python.org/pep-0308/) 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:[\[16\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-16)
```
result = x if a > b else y
```
This form invites considering `x` as the normal value and `y` as an exceptional case.
Being an [expression-oriented programming language](https://en.wikipedia.org/wiki/Expression-oriented_programming_language "Expression-oriented programming language"), 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[\[17\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-17) due to duplication with `if`.[\[18\]](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_note-18)
Note the lack of semi-colons in the code below compared to a more declarative `if`...`else` block, and the semi-colon at the end of the assignment to `y`.
```
let x = 5;
let y = if x == 5 {
10
} else {
15
};
```
This could also be written as:
```
let y = if x == 5 { 10 } else { 15 };
```
Note that curly braces are mandatory in Rust conditional expressions.
You could also use a `match` expression:
```
let y = match x {
5 => 10,
_ => 15,
};
```
Every expression (message send) has a value. Thus `ifTrue:ifFalse:` can be used:
```
|x y|
x := 5.
y := (x == 5) ifTrue:[10] ifFalse:[15].
```
The SQL `CASE` 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;
```
[Visual Basic](https://en.wikipedia.org/wiki/Visual_Basic "Visual Basic") provides a ternary conditional function, `IIf`, as shown in the following code:
```
Dim opening_time As Integer = IIf((day = SUNDAY), 12, 9)
```
As a function, the values of the three arguments are evaluated before the function is called. To avoid evaluating the expression that is not selected, the `If` keyword was added (in Visual Basic .Net 9.0) as a true ternary conditional operator. This allows the following code to avoid an exception if it were implemented with `IIf` instead:
```
Dim name As String = If(person Is Nothing, "", person.Name)
```
- [Conditioned disjunction](https://en.wikipedia.org/wiki/Conditioned_disjunction "Conditioned disjunction")
- [Elvis operator](https://en.wikipedia.org/wiki/Elvis_operator "Elvis operator") – Binary operator in computer programming
- [McCarthy Formalism](https://en.wikipedia.org/wiki/McCarthy_Formalism "McCarthy Formalism") – Computer science and recursion theory
- [Multiplexer](https://en.wikipedia.org/wiki/Multiplexer "Multiplexer") – Device that selects between several analog or digital input signals
- [Null coalescing operator](https://en.wikipedia.org/wiki/Null_coalescing_operator "Null coalescing operator") – Binary operator in computer programming
- [Safe navigation operator](https://en.wikipedia.org/wiki/Safe_navigation_operator "Safe navigation operator") – Boolean operator
- [Three-way comparison](https://en.wikipedia.org/wiki/Three-way_comparison "Three-way comparison") (one numeric expression selects one of three statements or branches)
1. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-1)**
[Strachey, Christopher](https://en.wikipedia.org/wiki/Christopher_Strachey "Christopher Strachey") (2000). "[Fundamental Concepts in Programming Languages](https://en.wikipedia.org/wiki/Fundamental_Concepts_in_Programming_Languages "Fundamental Concepts in Programming Languages")". *[Higher-Order and Symbolic Computation](https://en.wikipedia.org/wiki/Higher-Order_and_Symbolic_Computation "Higher-Order and Symbolic Computation")*. **13** (1–2\): 11–49\. [doi](https://en.wikipedia.org/wiki/Doi_\(identifier\) "Doi (identifier)"):[10\.1023/A:1010000313106](https://doi.org/10.1023%2FA%3A1010000313106). [S2CID](https://en.wikipedia.org/wiki/S2CID_\(identifier\) "S2CID (identifier)") [14124601](https://api.semanticscholar.org/CorpusID:14124601).
2. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-2)**
"5.5 Conditional expressions". [*The BCPL Reference Manual*](https://web.archive.org/web/20160316100234/http://www.eah-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf) (PDF). 1967. pp. 16–17\. Archived from [the original](http://www.eah-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf) (PDF) on 2016-03-16. Retrieved 2017-03-15.
3. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-3)**
Wastl, Eric. ["Ternary operator associativity"](http://phpsadness.com/sad/30). *phpsadness.com*. PHP Sadness. Retrieved 20 September 2017.
4. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-4)** <https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary>
5. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-5)**
["Rationale for Ada 2012"](http://www.ada-auth.org/standards/12rat/html/Rat12-2-1.html). ACAA. Retrieved 10 December 2015.
6. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-ISO/IEC_9899:1999_6-0)** ISO.IEC 9899:1999 (E) 6.5.15.4
7. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-java_7-0)** Java 7 Specification: [15\.25 Conditional Operator ? :](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25)
8. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-8)**
mikeblome. ["Conditional Operator: ?"](https://docs.microsoft.com/en-us/cpp/cpp/conditional-operator-q). *docs.microsoft.com*. Retrieved 2019-04-29.
9. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-:0_9-0)**
BillWagner. ["?: Operator - C\# Reference"](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator). *docs.microsoft.com*. Retrieved 2019-04-29.
10. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-10)**
["Conditional Operator"](http://wiki.c2.com/?ConditionalOperator). *wiki.c2.com*. Retrieved 2019-04-29.
11. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-11)**
["Kotlin Lang If Expression"](https://kotlinlang.org/docs/control-flow.html#if-expression). *kotlinlang.org*. Retrieved 2021-04-25.
12. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-12)**
["Syntax § If-then-else expressions"](https://luau.org/syntax#if-then-else-expressions). *Luau*. Retrieved 2023-02-07.
13. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-13)**
["if then (else) expressions"](https://www.delphitools.info/2013/01/08/if-then-else-expressions/). *DelphiTools*. Retrieved 11 September 2025.
14. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-14)**
["Coming in RAD Studio 13: A Conditional Ternary Operator for the Delphi Language"](https://blogs.embarcadero.com/coming-in-rad-studio-13-a-conditional-ternary-operator-for-the-delphi-language/). *Embarcadero Blogs*. 30 July 2025. Retrieved 11 September 2025.
15. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-15)**
["Texas, Start Your Photocopiers"](https://blogs.remobjects.com/2025/09/10/texas-start-your-photocopiers/). *RemObjects Blog*. Retrieved 11 September 2025.
16. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-16)**
["The Python Language Reference"](https://docs.python.org/3/reference/expressions.html#conditional-expressions).
17. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-17)**
["Remove Ternary Operator by pwoolcoc · Pull Request \#1705 · rust-lang/Rust"](https://github.com/rust-lang/rust/pull/1705). *[GitHub](https://en.wikipedia.org/wiki/GitHub "GitHub")*.
18. **[^](https://en.wikipedia.org/wiki/Ternary_conditional_operator#cite_ref-18)**
["Remove ternary operator · Issue \#1698 · rust-lang/Rust"](https://github.com/rust-lang/rust/issues/1698). *[GitHub](https://en.wikipedia.org/wiki/GitHub "GitHub")*.
- [Description of If operator in Visual Basic](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator)
- [Description of Conditional Expression in Python (PEP 308)](https://peps.python.org/pep-0308/)
- [Description in the Java Language Specification](https://docs.oracle.com/javase/specs/#15.25)
- [Description in the PHP Language Documentation](https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary) |
| Shard | 152 (laksa) |
| Root Hash | 17790707453426894952 |
| Unparsed URL | org,wikipedia!en,/wiki/Ternary_conditional_operator s443 |