{{Short description|Conditional operator in computer programming}} {{Redirect|?:|use as a binary operator|Elvis operator}} {{Redirect|Conditional operator|the {{code|<nowiki>||</nowiki>}} and {{code|&&}} operators, sometimes called conditional operators in Java and C#|Short-circuit evaluation}}
In computer programming, the '''ternary conditional operator''' is a conditional expression with three parts: the Boolean condition, the ''then''-expression, and the ''else''-expression. If the condition is true, the ''then''-expression is evaluated; otherwise, the ''else''-expression is evaluated; and the value is returned. Thus it is a non-strict operator, like other conditional expressions. It is also called a '''conditional operator''', '''ternary if''', '''immediate if''', or '''inline if''' ('''iif''').
Although a ternary operator in general is any operator with three arguments, the three-argument conditional operator is the only common one in programming, so it is loosely called ''the'' ternary operator.
C introduced the syntax {{code|a ? b : c}}, read as "if a then b otherwise c", which is widely used by other languages with C-like syntax. Some languages use functional syntax: in Visual Basic, it is written {{code|If(a, b, c)}}.
Many languages support conditional expressions with two, three, or more clauses. Languages following ALGOL-like syntax often support them with the same syntax as conditional statements, {{code|if a then b else c}}.
The construct first appeared in CPL in 1963, as <code>a → b, c</code>.<ref>{{cite journal|first=Christopher|last=Strachey|author-link=Christopher Strachey|title=Fundamental Concepts in Programming Languages|journal=Higher-Order and Symbolic Computation|volume=13|pages=11–49|year=2000|issue=1–2 |doi=10.1023/A:1010000313106|s2cid=14124601}}</ref><ref>{{cite book | url = http://www.eah-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf | title = The BCPL Reference Manual | year = 1967 | chapter = 5.5 Conditional expressions | pages = 16–17 | access-date = 2017-03-15 | archive-date = 2016-03-16 | archive-url = https://web.archive.org/web/20160316100234/http://www.eah-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf | url-status = dead }}</ref>
==Patterns==
===Assignment=== The value of the operator can be assigned to a variable. For a weakly typed language, the data type of the selected value may determine the type of the assigned value. For a strongly typed language, both value expressions must evaluate to a type that is compatible with the target variable.
The operator is similar to the way conditional expressions (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:
<syntaxhighlight lang="python"> x: str = 'foo' if b else 'bar' </syntaxhighlight>
instead of:
<syntaxhighlight lang="python"> x: str if b: x = 'foo' else: x = 'bar' </syntaxhighlight>
In a language with block scope, a variable must be declared before the if-else statement. For example:
<syntaxhighlight lang="cpp"> std::string s; if (b) { s = "foo"; } else { s = "bar"; } </syntaxhighlight>
Use of the conditional operator simplifies this:
<syntaxhighlight lang="cpp"> std::string s = b ? "foo" : "bar"; </syntaxhighlight>
Furthermore, since initialization is now part of the declaration, rather than a separate statement, the identifier can be a constant. For example:
<syntaxhighlight lang="cpp"> const std::string s = b ? "foo" : "bar"; </syntaxhighlight>
===Case selector=== The conditional operator can be used for case selectors. For example:
<syntaxhighlight lang="c"> vehicle = arg == 'B' ? bus : arg == 'A' ? airplane : arg == 'T' ? train : arg == 'C' ? car : arg == 'H' ? horse : feet; </syntaxhighlight>
==Variations== The syntax and semantics of the operator vary by language.
Major differences include whether the expressions can have side effects and whether the language provides short-circuit evaluation semantics, whereby only the selected expression is evaluated.
If a language supports expressions with side effects but does not specify short-circuit evaluation, then a further distinction exists about which expression evaluates first. If no order is guaranteed, a distinction exists about whether the result is then classified as indeterminate (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 {{en dash}} 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 {{code|1=r = condition ? expr1 : expr2}} can have subtly different semantics than the block conditional form {{code|1=if (condition) { r = expr1; } else { r = expr2; }|2=c}}.
In almost all languages, the ternary operator is right associative, so that {{code|1=a == 1 ? "one" : a == 2 ? "two" : "many"}} evaluates intuitively as {{code|1=a == 1 ? "one" : (a == 2 ? "two" : "many")}}. This means it can be chained similarly to an <code>if ... else if ... else if ... else</code> chain. The main exception is PHP, in which it was left-associative (such that the same expression evaluates to {{code|1=(a == 1 ? "one" : a == 2) ? "two" : "many"}}, which is rarely what the programmer expects)<ref>{{cite web |url=http://phpsadness.com/sad/30 |title=Ternary operator associativity |last1=Wastl |first1=Eric |website=phpsadness.com |publisher=PHP Sadness |access-date=20 September 2017}}</ref> prior to version 8, and is non-associative thereafter.<ref>https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary</ref>
Furthermore, in all C-family languages and many others, the ternary conditional operator has low operator precedence.
==Examples==
===Ada=== The 2012 edition of Ada introduced conditional expressions (using {{code|if}} and {{code|case}}), as part of an enlarged set of expressions including quantified expressions and expression functions. The Rationale for Ada 2012<ref>{{cite web|title=Rationale for Ada 2012|url=http://www.ada-auth.org/standards/12rat/html/Rat12-2-1.html|publisher=ACAA|access-date=10 December 2015}}</ref> states motives for Ada not having had them before, as well as motives for now adding them, such as to support "contracts" (also new).
<syntaxhighlight lang="ada"> Pay_per_Hour := (if Day = Sunday then 12.50 else 10.00); </syntaxhighlight>
When the value of an ''if_expression'' is itself of Boolean type, then the {{code|else}} part may be omitted, the value being True. Multiple conditions may chained using {{code|elsif}}.
===ALGOL 60===
ALGOL 60 introduced conditional expressions (ternary conditionals) to imperative programming languages.
This conditional statement:
<syntaxhighlight lang="pascal"> integer opening_time; if day = Sunday then opening_time := 12; else opening_time := 9; </syntaxhighlight>
Can be rewritten with the conditional operator:
<syntaxhighlight lang="pascal"> integer opening_time; opening_time := if day = Sunday then 12 else 9; </syntaxhighlight>
===ALGOL 68=== Both ALGOL 68's choice clauses (if and case clauses) support the following:
; Single if choice clause: {{code |if condition then statements [ else statements ] fi}} or a brief form: <code>( condition | statements | statements )</code>
; Chained if choice clause: {{code |if condition1 then statements elif condition2 then statements [ else statements ] fi}} or a brief form: <code>( condition1 | statements |: condition2 | statements | statements )</code>.
===Bash=== A true ternary operator exists for arithmetic expressions:
<syntaxhighlight lang="bash"> ((result = condition ? value_if_true : value_if_false)) </syntaxhighlight>
For strings there are workarounds, like e.g.:
<syntaxhighlight lang="bash"> result=$(if condition ; then echo "value_if_true" ; else echo "value_if_false" ; fi) </syntaxhighlight>
Where {{code|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=== The following code in C assigns {{code |result}} to the value of <code>x</code> if <code>a > b</code>, and otherwise to the value of <code>y</code>. This is the same syntax as in many related languages including C++, Java, JavaScript, and Dart.
<syntaxhighlight lang="c"> result = a > b ? x : y; </syntaxhighlight>
Only the selected expression is evaluated. In this example, <code>x</code> and <code>y</code> require no evaluation, but they can be expressions with side effects. Only the side-effect for the selected expression value will occur.<ref name="ISO/IEC 9899:1999">ISO.IEC 9899:1999 (E) 6.5.15.4</ref><ref name="java">Java 7 Specification: [https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25 15.25 Conditional Operator ? : ]</ref>
If <code>x</code> and <code>y</code> 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 <code>x</code> and <code>y</code> 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.<ref>{{Cite web|url=https://docs.microsoft.com/en-us/cpp/cpp/conditional-operator-q|title=Conditional Operator: ?|last=mikeblome|website=docs.microsoft.com|language=en-us|access-date=2019-04-29}}</ref> * In C#, if one expression is implicitly convertible to the type of the other, that type is used. Otherwise, a compile-time error occurs.<ref name=":0">{{Cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator|title=?: Operator - C# Reference|last=BillWagner|website=docs.microsoft.com|language=en-us|access-date=2019-04-29}}</ref> * 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 <code>x</code> and <code>y</code> are lvalues, though this is rarely used in practice:<ref>{{Cite web|url=http://wiki.c2.com/?ConditionalOperator|title=Conditional Operator|website=wiki.c2.com|access-date=2019-04-29}}</ref> <syntaxhighlight lang="c++"> (foo ? bar : baz) = frink; </syntaxhighlight>
===Common Lisp=== Assignment using a conditional expression in Common Lisp:
<syntaxhighlight lang="lisp"> (setq result (if (> a b) x y)) </syntaxhighlight>
Alternative form:
<syntaxhighlight lang="lisp"> (if (> a b) (setq result x) (setq result y)) </syntaxhighlight>
===dBASE=== In dBase, the conditional function <code>iif(<expL>, <expT>, <expF>)</code> is called "Immediate IF". It uses shortcut evaluation (it only evaluates one of {{mono|<expT>}} or {{mono|<expF>}}).
For example, to sort a list by the street name and then (in most cases) house number, one could type {{codett|index on iif(instr(addr," ") , substr(addr,instr(addr," ")+1,10) + left(addr,instr(addr," ")-1) , addr)|vfp}} to indexfile at the dBASE III command prompt, and then copy or export the table.
===Fortran=== As part of the Fortran-90 Standard, the ternary operator was added to Fortran as the intrinsic function {{code|merge}}:
<syntaxhighlight lang="fortran"> variable = merge(x,y,a>b) </syntaxhighlight>
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:
<syntaxhighlight lang="fortran"> variable = ( a > b ? x : y ) </syntaxhighlight>
=== Kotlin === Kotlin does not include the traditional {{code|?:}} ternary operator, however, an {{code |if}} can be used as an expression that can be assigned,<ref>{{Cite web|url=https://kotlinlang.org/docs/control-flow.html#if-expression|title=Kotlin Lang If Expression|website=kotlinlang.org|access-date=2021-04-25}}</ref> achieving the same results.
<syntaxhighlight lang="kotlin"> val max = if (a > b) a else b </syntaxhighlight>
=== Lua === Lua does not have a traditional conditional operator. However, the short-circuiting behavior of its {{code|and}} and {{code|or}} operators allows the emulation of this behaviour. The following is equivalent to: <code>var = cond ? a : b</code>.
<syntaxhighlight lang="lua"> var = cond and a or b </syntaxhighlight>
This will succeed unless {{code |a}} is logically false; in this case, the expression will always result in {{code |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:
<syntaxhighlight lang="lua"> var = ( { [true] = a, [false] = b } )[not not cond] </syntaxhighlight>
Luau, a dialect of Lua, has ternary expressions that look like if statements, but unlike them, they have no {{code|lang=luau|end}} keyword, and the {{code|lang=luau|else}} clause is required. One may optionally add {{code|lang=luau|elseif}} clauses. It's designed to replace the {{code|lang=lua|cond and a or b}} idiom and is expected to work properly in all cases.<ref>{{cite web |title=Syntax § If-then-else expressions|url=https://luau.org/syntax#if-then-else-expressions |access-date=2023-02-07 |website=Luau |language=en}}</ref>
<syntaxhighlight lang="luau"> -- 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 </syntaxhighlight>
=== Object Pascal extensions === Pascal was both a simplification and extension of ALGOL 60, but it removed conditional expressions.
RemObjects Oxygene added a ternary operator to Object Pascal in approximately 2011,<ref>{{cite web |url=https://www.delphitools.info/2013/01/08/if-then-else-expressions/ |website=DelphiTools |access-date=11 September 2025 |title=if then (else) expressions}}</ref> and in 2025 Delphi followed suit.<ref>{{cite web |url=https://blogs.embarcadero.com/coming-in-rad-studio-13-a-conditional-ternary-operator-for-the-delphi-language/ |website=Embarcadero Blogs |access-date=11 September 2025 |title=Coming in RAD Studio 13: A Conditional Ternary Operator for the Delphi Language |date=30 July 2025 }}</ref> Oxygene supports case/switch statements, essentially a repeated if, as expressions evaluating to a value as well.<ref>{{cite web |url=https://blogs.remobjects.com/2025/09/10/texas-start-your-photocopiers/ |website=RemObjects Blog |access-date=11 September 2025 |title=Texas, Start Your Photocopiers }}</ref>
===Python=== Python has had a ternary conditional expression since release 2.5 (September 2006).<ref>[https://peps.python.org/pep-0308/ Python Enhancement Proposal 308]</ref> Python's conditional operator differs from the C-style {{code|?:}} operator in the order of its operands. The general form is:<ref>{{cite web|url=https://docs.python.org/3/reference/expressions.html#conditional-expressions | title=The Python Language Reference}}</ref>
<syntaxhighlight lang="python"> result = x if a > b else y </syntaxhighlight>
This form invites considering {{code |x}} as the normal value and {{code |y}} as an exceptional case. Unlike Python conditional statements, the <code>elif</code> clause is not supported, but nested conditional expressions are allowed.
===Rust=== As an expression-oriented programming language, all Rust conditionals are expressions, not statements, so the <code>if ''expr<sub>1</sub>'' else ''expr<sub>2</sub>''</code> syntax behaves like the C-style {{code|?:}} ternary operator. Earlier versions of the language had a {{code|?:}} operator but it was removed<ref>{{Cite web|url=https://github.com/rust-lang/rust/pull/1705|title = Remove Ternary Operator by pwoolcoc · Pull Request #1705 · rust-lang/Rust|website = GitHub}}</ref> due to duplication with {{code|if}}.<ref>{{Cite web|url=https://github.com/rust-lang/rust/issues/1698|title=Remove ternary operator · Issue #1698 · rust-lang/Rust|website=GitHub}}</ref>
Note the lack of semi-colons in the code below compared to an imperative {{code|if}}...{{code|else}} block, and the semi-colon at the end of the assignment to {{code|y}}.
<syntaxhighlight lang="rust"> let x = 5;
let y = if x == 5 { 10 } else { 15 }; </syntaxhighlight>
This could also be written as:
<syntaxhighlight lang="rust"> let y = if x == 5 { 10 } else { 15 }; </syntaxhighlight>
Curly braces are mandatory in Rust conditional expressions.
You could also use a {{code|match}} expression:
<syntaxhighlight lang="rust"> let y = match x { 5 => 10, _ => 15, }; </syntaxhighlight>
===Smalltalk=== Every expression (message send) has a value. Thus {{code|ifTrue:ifFalse:}} can be used:
<syntaxhighlight lang="scheme"> |x y|
x := 5. y := (x == 5) ifTrue:[10] ifFalse:[15]. </syntaxhighlight>
===SQL=== The SQL {{code|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:
<syntaxhighlight lang="sql"> SELECT (CASE WHEN a > b THEN x ELSE y END) AS CONDITIONAL_EXAMPLE FROM tab; </syntaxhighlight>
This can be expanded to several conditionals:
<syntaxhighlight lang="sql"> SELECT (CASE WHEN a > b THEN x WHEN a < b THEN y ELSE z END) AS CONDITIONAL_EXAMPLE FROM tab; </syntaxhighlight>
===Visual Basic=== Visual Basic provides a ternary conditional function, {{code |IIf}}, as shown in the following code:
<syntaxhighlight lang="vbnet"> Dim opening_time As Integer = IIf((day = SUNDAY), 12, 9) </syntaxhighlight>
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 {{code |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 {{code |IIf}} instead:
<syntaxhighlight lang="vbnet"> Dim name As String = If(person Is Nothing, "", person.Name) </syntaxhighlight>
==See also== * {{Annotated link |Conditioned disjunction}} * {{Annotated link |Elvis operator}} * {{Annotated link |McCarthy Formalism}} * {{Annotated link |Multiplexer}} * {{Annotated link |Null coalescing operator}} * {{Annotated link |Safe navigation operator}} * Three-way comparison (one numeric expression selects one of three statements or branches)
==References== {{Reflist|35em}}
==External links== * [https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator Description of If operator in Visual Basic] * [https://peps.python.org/pep-0308/ Description of Conditional Expression in Python (PEP 308)] * [https://docs.oracle.com/javase/specs/#15.25 Description in the Java Language Specification] * [https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary Description in the PHP Language Documentation]
Category:Conditional constructs Category:Operators (programming) Category:Ternary operations Category:Articles with example code