|| and&& operators, sometimes called conditional operators in Java and C#, seeShort-circuit evaluation.Incomputer programming, theternary conditional operator is aternary operator that evaluates to one of two values based on aBoolean expression. The operator is also known asconditional operator,ternary if,immediate if, orinline 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 asthe ternary operator.
Typical syntax for anexpression using the operator is likeif a then b else c ora ? b : c. One can read it aloud as "if a then b otherwise c". The forma ? b : c is the most common, but alternative syntax exists. For example,Raku uses the syntaxa ?? b !! c to avoid confusion with the infix operators? and!, whereas inVisual Basic, it takes the formIf(a, b, c).
The construct first appeared inCPL, in which equivalent syntax fora ? b : c isa → b, c.[1][2]
The value of the operator can be assigned to a variable. For a weakly typed language, thedata 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 infunctional programming languages, likeScheme,ML,Haskell, andXQuery, 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'ifbelse'bar'
instead of:
x:strifb:x='foo'else:x='bar'
In a language withblock scope, a variable must be declared before the if-else statement. For example:
std::strings;if(b){s="foo";}else{s="bar";}
Use of the conditional operator simplifies this:
std::strings=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:
conststd::strings=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 haveside effects and whether the language providesshort-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 fromsome order) orundefined (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 formr = condition ? expr1 : expr2 can have subtly different semantics than the block conditional formif(condition){r=expr1;}else{r=expr2;}.
In almost all languages, the ternary operator isright associative, so thata == 1 ? "one" : a == 2 ? "two" : "many" evaluates intuitively asa == 1 ? "one" : (a == 2 ? "two" : "many"). This means it can be chained similarly to anif ... else if ... else if ... else chain. The main exception isPHP, 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 lowoperator 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 expressionc(expr1,expr2)[1+condition] (this idiom is slightly more natural in languages with 0-origin subscripts).Nested ternaries can be simulated asc(expr1,expr2,expr3)[which.first((c(cond1,cond2,TRUE))] where the functionwhich.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 ofcurrying based on data concatenation rather than function composition.
If the language provides a mechanism offutures or promises, then short-circuit evaluation can sometimes also be simulated in the context of a binary map operation.
The 2012 edition ofAda has introduced conditional expressions (usingif andcase), 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:=(ifDay=Sundaythen12.50else10.00);
When the value of anif_expression is itself of Boolean type, then theelse part may be omitted, the value being True. Multiple conditions may chained usingelsif.
ALGOL 60 introducedconditional expressions (ternary conditionals) toimperative programming languages.
This conditional statement:
integeropening_time;ifday=Sundaythenopening_time:=12;elseopening_time:=9;
Can be rewritten with the conditional operator:
integeropening_time;opening_time:=ifday=Sundaythen12else9;
BothALGOL 68'schoice clauses (if and case clauses) support the following:
if condition then statements [ else statements ] fi or a brief form:( condition | statements | statements )if condition1 then statements elif condition2 then statements [ else statements ] fi or a brief form:( condition1 | statements |: condition2 | statements | statements ).A true ternary operator only exists for arithmetic expressions:
((result=condition?value_if_true:value_if_false))
For strings there only exist workarounds, like e.g.:
result=$([["$a"="$b"]]&&echo"value_if_true"||echo"value_if_false")
Where"$a" = "$b" can be any condition[[ … ]] construct can evaluate. Instead of the[[ … ]] there can be any other bash command. When it exits with success, the first echo command is executed, otherwise the second one is executed.
The following code inC assignsresult to the value ofx ifa > b, and otherwise to the value ofy. This is the same syntax as in many related languages includingC++,Java,JavaScript, andDart.
result=a>b?x:y;
Only the selected expression is evaluated. In this example,x andy require no evaluation, but they can be expressions withside effects. Only the side-effect for the selected expression value will occur.[6][7]
Ifx andy 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:
x andy 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]Furthermore, in C++, a conditional expression can be used as anlvalue, if bothx andy are lvalues, though this is rarely used in practice:[10]
(foo?bar:baz)=frink;
Assignment using a conditional expression inCommon Lisp:
(setqresult(if(>ab)xy))
Alternative form:
(if(>ab)(setqresultx)(setqresulty))
IndBase, the conditional functioniif(<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 oniif(instr(addr," ") ,substr(addr,instr(addr," ")+1,10) +left(addr,instr(addr," ")-1) , addr) to indexfileat the dBASE III command prompt, and then copy or export the table.
As part of the Fortran-90 Standard, the ternary operator was added toFortran as the intrinsic functionmerge:
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, anif can be used as an expression that can be assigned,[11] achieving the same results.
valmax=if(a>b)aelseb
Lua does not have a traditional conditional operator. However, the short-circuiting behavior of itsand andor operators allows the emulation of this behaviour. The following is equivalent to:var = cond ? a : b.
var=condandaorb
This will succeed unlessa is logically false; in this case, the expression will always result inb. 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})[notnotcond]
Luau, a dialect of Lua, has ternary expressions that look like if statements, but unlike them, they have noend keyword, and theelse clause is required. One may optionally addelseif clauses. It's designed to replace thecondandaorb idiom and is expected to work properly in all cases.[12]
-- in Luauvar=ifcondthenaelseb-- with elseif clausesign=ifvar<0then-1elseifvar==0then0else1
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 supportscase/switch statements, essentially a repeated if, as expressions evaluating to a value as well.[15]
An operator for a conditional expression inPython was approved asPython 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=xifa>belsey
This form invites consideringx as the normal value andy as an exceptional case.
Being anexpression-oriented programming language, Rust's existingifexpr1 elseexpr2 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 withif.[18]
Note the lack of semi-colons in the code below compared to a more declarativeif...else block, and the semi-colon at the end of the assignment toy.
letx=5;lety=ifx==5{10}else{15};
This could also be written as:
lety=ifx==5{10}else{15};
Note that curly braces are mandatory in Rust conditional expressions.
You could also use amatch expression:
lety=matchx{5=>10,_=>15,};
Every expression (message send) has a value. ThusifTrue:ifFalse: can be used:
|xy|x:=5.y:=(x==5)ifTrue:[10]ifFalse:[15].
The SQLCASE expression is a generalization of the ternary operator. Instead of one conditional and two results,n conditionals andn+1 results can be specified.
With one conditional it is equivalent (although more verbose) to the ternary operator:
SELECT(CASEWHENa>bTHENxELSEyEND)ASCONDITIONAL_EXAMPLEFROMtab;
This can be expanded to several conditionals:
SELECT(CASEWHENa>bTHENxWHENa<bTHENyELSEzEND)ASCONDITIONAL_EXAMPLEFROMtab;
Visual Basic provides a ternary conditional function,IIf, as shown in the following code:
Dimopening_timeAsInteger=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, theIf 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 withIIf instead:
DimnameAsString=If(personIsNothing,"",person.Name)