In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, conditional expression, ternary if, or inline if (abbreviated iif). An expression if a then b else c or a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to oid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).
It originally comes from CPL, in which equivalent syntax for e1 ? e2 : e3 was e1 → e2, e3.[1][2]
Although many ternary operators are possible, the conditional operator is so common, and other ternary operators so rare, that the conditional operator is commonly referred to as the ternary operator.
Variations[edit]The detailed semantics of "the" ternary operator as well as its syntax differs significantly from language to language.
A top level distinction from one language to another is whether the expressions permit side effects (as in most procedural languages) and whether the language provides short-circuit evaluation semantics, whereby only the selected expression is evaluated (most standard operators in most languages evaluate all arguments).
If the language supports expressions with side effects but does not specify short-circuit evaluation, then a further distinction exists about which expression evaluates first—if the language guarantees any specific order (bear in mind that the conditional also counts as an expression).
Furthermore, if no order is guaranteed, a distinction exists about whether the result is then classified as indeterminate (the value obtained from some order) or undefined (any value at all at the whim of the compiler in the face of side effects, or even a crash).
If the language does not permit side-effects in expressions (common in functional languages), then the order of evaluation has no value semantics—though it may yet bear on whether an infinite recursion terminates, or he 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 variable = condition ? expr1 : expr2; can he subtly different semantics than the block conditional form if (condition) { variable = expr1; } else { variable = expr2; } (in the C language—the syntax of the example given—these are in fact equivalent).
The associativity of nested ternary operators can also differ from language to language. In almost all languages, the ternary operator is right associative so that a == 1 ? "one" : a == 2 ? "two" : "many" evaluates intuitively as a == 1 ? "one" : (a == 2 ? "two" : "many"), but PHP in particular is notoriously left-associative,[3] and evaluates as follows: (a == 1 ? "one" : a == 2) ? "two" : "many", which is rarely what any programmer expects. (The given examples assume that the ternary operator has low operator precedence, which is true in all C-family languages, and many others.)
Equivalence to map[edit]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.
Conditional assignment[edit]Originally from ALGOL 60 the conditional assignment of ALGOL is:
variable := if condition then expression_1 else expression_2;?: is used as follows:
condition ? value_if_true : value_if_falseThe condition is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value_if_true if condition is true, but value_if_false otherwise. Usually the two sub-expressions value_if_true and value_if_false must he the same type, which determines the type of the whole expression. The importance of this type-checking lies in the operator's most common use—in conditional assignment statements. In this usage it appears as an expression on the right side of an assignment statement, as follows:
variable = condition ? value_if_true : value_if_false;The ?: operator is similar to the way conditional expressions (if-then-else constructs) work in functional programming languages, like Scheme, ML, Haskell, and XQuery, since if-then-else forms an expression instead of a statement in those languages.
Usage[edit]The conditional operator's most common usage is to create a terse, simple conditional assignment. For example, if we wish to implement some C code to change a shop's normal opening hours from 9 o'clock to 12 o'clock on Sundays, we may use
int opening_time = (day == SUNDAY) ? 12 : 9;instead of the more verbose
int opening_time; if (day == SUNDAY) { opening_time = 12; } else { opening_time = 9; }The two forms are nearly equivalent. Keep in mind that the ?: is an expression and if-then-else is a statement. Note that neither the true nor false portions can be omitted from the conditional operator without an error report upon parsing. This contrasts with if-then-else statements, where the else clause can be omitted.
Most of the languages emphasizing functional programming don't need such an operator as their regular conditional expression(s) is an expression in the first place e.g. the Scheme expression (if (> a b) a b) is equivalent in semantics to the C expression (a > b) ? a : b. This is also the case in many imperative languages, starting with ALGOL where it is possible to write result := if a > b then a else b, or Smalltalk (result := (a > b) ifTrue: [ a ] ifFalse: [ b ]) or Ruby (result = if a > b then a else b end, although result = a > b ? a : b works as well).
Note that some languages may evaluate both the true- and false-expressions, even though only one or the other will be assigned to the variable. This means that if the true- or false-expression contain a function call, that function may be called and executed (causing any related side-effects due to the function's execution), regardless of whether or not its result will be used. Programmers should consult their programming language specifications or test the ternary operator to determine whether or not the language will evaluate both expressions in this way. If it does, and this is not the desired behiour, then an if-then-else statement should be used.
ActionScript 3[edit] condition ? value_if_true : value_if_false Ada[edit]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[4] states motives for Ada not hing 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]ALGOL 60 introduced conditional expressions (thus ternary conditionals) to imperative programming languages.
if then elseRather than a conditional statement:
integer opening_time; if day = Sunday then opening_time := 12; else opening_time := 9;the programmer could use the conditional expression to write more succinctly:
integer opening_time; opening_time := if day = Sunday then 12 else 9; ALGOL 68[edit]Both ALGOL 68's choice clauses (if and the case clauses) provide the coder with a choice of either the "bold" syntax or the "brief" form.
Single if choice clause: if condition then statements [ else statements ] fi "brief" form: ( condition | statements | statements ) Chained if choice clause: if condition1 then statements elif condition2 then statements [ else statements ] fi "brief" form: ( condition1 | statements |: condition2 | statements | statements ) APL[edit]With the following syntax, both expressions are evaluated (with value_if_false evaluated first, then condition, then value_if_false):
result ← value_if_true ⊣⍣ condition ⊢ value_if_falseThis alternative syntax provides short-circuit evaluation:
result ← { condition : expression_if_true ⋄ expression_if_false } ⍬ AWK[edit] result = condition ? value_if_true : value_if_false Bash[edit]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.
C[edit]A traditional if-else construct in C is written:
if (a > b) { result = x; } else { result = y; }This can be rewritten as the following statement:
result = a > b ? x : y;As in the if-else construct only one of the expressions 'x' and 'y' is evaluated. This is significant if the evaluation of 'x' or 'y' has side effects.[5] The behiour is undefined if an attempt is made to use the result of the conditional operator as an lvalue.[5]
A GNU extension to C allows omitting the second operand, and using implicitly the first operand as the second also:
a = x ? : y;The expression is equivalent to
a = x ? x : y;except that expressions a and x are evaluated only once. The difference is significant if evaluating the expression has side effects. This shorthand form is sometimes known as the Elvis operator in other languages.
C#[edit]In C#, if condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. As with Ja only one of two expressions is ever evaluated.
// condition ? first_expression : second_expression; static double Sinc(double x) { return x != 0.0 ? Math.Sin(x) / x : 1.0; } C++[edit]Unlike in C, the precedence of the ?: operator in C++ is the same as that of the assignment operator (= or OP =), and it can return an lvalue.[6] This means that expressions like q ? a : b = c and (q ? a : b) = c are both legal and are parsed differently, the former being equivalent to q ? a : (b = c).
In C++ there are conditional assignment situations where use of the if-else statement is impossible, since this language explicitly distinguishes between initialization and assignment. In such case it is always possible to use a function call, but this can be cumbersome and inelegant. For example, to pass conditionally different values as an argument for a constructor of a field or a base class, it is impossible to use a plain if-else statement; in this case we can use a conditional assignment expression, or a function call. Bear in mind also that some types allow initialization, but do not allow assignment, or even that the assignment operator and the constructor do totally different things. This last is true for reference types, for example:
import std; using std::ios; using std::ofstream; using std::string; int main(int argc, char* argv[]) { string name; ofstream myFile; if (argc > 1 && argv[1]) { name = argv[1]; myFile.open(name, ios::out | ios::app); } ostream& myOutputStream = name.empty() ? stdout : myFile; std::println(myOutputStream, "Hello, world!"); return 0; }In this case, using an if-else statement in place of the ?: operator forces the target of the assignment to be declared outside of the branches as a pointer, which can be freely rebound to different objects.
ostream* myOutputStream = &myFile; if (name.empty()) { myOutputStream = &stdout; } std::println(*myOutputStream, "Hello, world!");In this simple example, the myOutputStream pointer can be initialized to a default value, mitigating the risk of leing pointers uninitialized or null. Nevertheless, there are cases when no good default exists or creating a default value is expensive. More generally speaking, keeping track of a nullable pointer increases cognitive load. Therefore, only conditional assignment to a reference through the ?: operator conveys the semantics of Initializing a variable from only one of two choices based on a predicate appropriately.
Furthermore, the conditional operator can yield an lvalue, i.e. a value to which another value can be assigned. Consider the following example:
import std; int main(int argc, char* argv[]) { int a = 0; int b = 0; (argc > 1 ? a : b) = 1; std::println("a: {} b: {}", a, b); return 0; }In this example, if the boolean expression argc > 1 yields the value true on line 7, the value 1 is assigned to the variable a, otherwise the value 1 is assigned to the variable b.
CFML[edit]Example of the ?: operator in CFML:
result = randRange(0,1) ? "heads" : "tails";Roughly 50% of the time the randRange() expression will return 1 (true) or 0 (false); meaning result will take the value "heads" or "tails" respectively.
Lucee, Railo, and ColdFusion 11-specific[edit]Lucee, Railo, and ColdFusion 11 also implement the Elvis operator, ?: which will return the value of the expression if it is not-null, otherwise the specified default.
Syntax:
result = expression ?: value_if_expression_is_nullExample:
result = f() ?: "default"; // where... function f(){ if (randRange(0,1)){ // either 0 or 1 (false / true) return "value"; } } writeOutput(result);The function f() will return value roughly 50% of the time, otherwise will not return anything. If f() returns "value", result will take that value, otherwise will take the value "default".
CoffeeScript[edit]Example of using this operator in CoffeeScript:
if 1 is 2 then "true value" else "false value"Returns "false value".
Common Lisp[edit]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)) Crystal[edit]Example of using this operator in Crystal:
1 == 2 ? "true value" : "false value"Returns "false value".
The Crystal compiler transforms conditional operators to if expressions, so the above is semantically identical to:
if 1 == 2 "true value" else "false value" end Dart[edit]The Dart programming language's syntax belongs to the C family, primarily inspired by languages like Ja, C# and JaScript, which means it has inherited the traditional ?: syntax for its conditional expression.
Example:
return x.isEven ? x ~/ 2 : x * 3 + 1;Like other conditions in Dart, the expression before the ? must evaluate to a Boolean value.
The Dart syntax uses both ? and : in various other ways, which causes ambiguities in the language grammar. An expression like:
{ x as T ? [1] : [2] }could be parsed as either a "set literal" containing one of two lists or as a "map literal" {((x as T?)[1]) : [2]}. The language always chooses the conditional expression in such situations.
Dart also has a second ternary operator, the []= operator commonly used for setting values in lists or maps, which makes the term "the ternary operator" ambiguous in a Dart context.
Delphi[edit]In Delphi the IfThen function can be used to achieve the same as ?:. If the System.Math library is used, the IfThen function returns a numeric value such as an Integer, Double or Extended. If the System.StrUtils library is used, this function can also return a string value.
Using System.Math
function IfThen(alue: Boolean; const ATrue: Integer; const AFalse: Integer): Integer; function IfThen(alue: Boolean; const ATrue: Int64; const AFalse: Int64): Int64; function IfThen(alue: Boolean; const ATrue: UInt64; const AFalse: UInt64): UInt64; function IfThen(alue: Boolean; const ATrue: Single; const AFalse: Single): Single; function IfThen(alue: Boolean; const ATrue: Double; const AFalse: Double): Double; function IfThen(alue: Boolean; const ATrue: Extended; const AFalse: Extended): Extended;Using the System.StrUtils library
function IfThen(alue: Boolean; const ATrue: string; AFalse: string = ''): string;Usage example:
function GetOpeningTime(Weekday: Integer): Integer; begin { This function will return the opening time for the given weekday: 12 for Sundays, 9 for other days } Result := IfThen((Weekday = 1) or (Weekday = 7), 12, 9); end;Unlike a true ternary operator however, both of the results are evaluated prior to performing the comparison. For example, if one of the results is a call to a function which inserts a row into a database table, that function will be called whether or not the condition to return that specific result is met.
Eiffel[edit]The original Eiffel pure OO language from 1986 did not he conditional expressions. Extensions to Eiffel to integrate the style and benefits of functional in the form of agents (closely associated with functional lambdas) were proposed and implemented in 2014.
if then else opening_time: INTEGER opening_time := if day = Sunday then 12 else 9 F#[edit]In F# the built-in syntax for if-then-else is already an expression that always must return a value.
let num = if x = 10 then 42 else 24F# has a special case where you can omit the else branch if the return value is of type unit. This way you can do side-effects, without using an else branch.
if x = 10 then printfn "It is 10"But even in this case, the if expression would return unit. You don't need to write the else branch, because the compiler will assume the unit type on else.
FORTH[edit]Since FORTH is a stack-oriented language, and any expression can lee a value on the stack, all IF/ELSE/THEN sequences can generate values:
: test ( n -- n ) 1 AND IF 22 ELSE 42 THEN ;This word takes 1 parameter on the stack, and if that number is odd, lees 22. If it's even, 42 is left on the stack.
Fortran[edit]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 has added conditional expressions which evaluate one or the other of the expressions based on the conditional expression:
variable = ( a > b ? x : y ) FreeMarker[edit]This built-in exists since FreeMarker 2.3.20.
Used like booleanExp?then(whenTrue, whenFalse), fills the same role as the ternary operator in C-like languages.
${(x > y)?then(x, y)} Go[edit]There is no ternary if in Go, so use of the full if statement is always required.[7]
Haskell[edit]The built-in if-then-else syntax is inline: the expression
if predicate then expr1 else expr2has type
Bool -> a -> a -> aThe base library also provides the function Data.Bool.bool:
bool :: a -> a -> Bool -> aIn both cases, no special treatment is needed to ensure that only the selected expression is evaluated, since Haskell is non-strict by default. This also means an operator can be defined that, when used in combination with the $ operator, functions exactly like ?: in most languages:
(?) :: Bool -> a -> a -> a (?) pred x y = if pred then x else y infix 1 ? -- example (vehicle will evaluate to "airplane"): arg = 'A' vehicle = arg == 'B' ? "boat" $ arg == 'A' ? "airplane" $ arg == 'T' ? "train" $ "car"However, it is more idiomatic to use pattern guards
-- example (vehicle will evaluate to "airplane"): arg = 'A' vehicle | arg == 'B' = "boat" | arg == 'A' = "airplane" | arg == 'T' = "train" | otherwise = "car" Ja[edit]In Ja this expression evaluates to:
// If foo is selected, assign selected foo to bar. If not, assign baz to bar. Object bar = foo.isSelected() ? foo : baz;Note that Ja, in a manner similar to C#, only evaluates the used expression and will not evaluate the unused expression.[8]
Julia[edit]In Julia, "Note that the spaces around ? and : are mandatory: an expression like a?b:c is not a valid ternary expression (but a newline is acceptable after both the ? and the :)."[9]
JaScript[edit]The conditional operator in JaScript is similar to that of C++ and Ja, except for the fact the middle expression cannot be a comma expression. Also, as in C++, but unlike in C or Perl, it will not bind tighter than an assignment to its right—q ? a : b = c is equivalent to q ? a : (b = c) instead of (q ? a : b) = c.[10]
var timeout = settings === null ? 1000 : settings.timeout;Just like C# and Ja, the expression will only be evaluated if, and only if, the expression is the matching one for the condition given; the other expression will not be evaluated.
Lisp[edit]As the first functional programming language, Lisp naturally has conditional expressions since there are no statements and thus not conditional statements. The form is:
(if test-expression then-expression else-expression)Hence:
(if (= day 'Sunday) 12 9) Kotlin[edit]Kotlin does not include the traditional ?: ternary operator, however, ifs can be used as expressions that can be assigned,[11] achieving the same results. Note that, as the complexity of one's conditional statement grows, the programmer might consider replacing their if-else expression with a when expression.
val max = if (a > b) a else b Lua[edit]Lua does not he a traditional conditional operator. However, the short-circuiting behiour of its and and or operators allows the emulation of this behiour:
-- equivalent to var = cond ? a : b; var = cond and a or bThis will succeed unless a is logically false (i.e. false or nil); in this case, the expression will always result in b. This can result in some surprising behiour if ignored.
There are also other variants that can be used, but they're generally more verbose:
-- parentheses around the table literal are required 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 he 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 $b ? $x : $y;The precedence of the conditional operator in Perl is the same as in C, not as in C++. This is conveniently of higher precedence than a comma operator but lower than the precedence of most operators used in expressions within the ternary operator, so the use of parentheses is rarely required.[13]
Its associativity matches that of C and C++, not that of PHP. Unlike C but like C++, Perl allows the use of the conditional expression as an L-value;[14] for example:
$a > $b ? $x : $y = $result;will assign $result to either $x or $y depending on the logical expression's boolean result.
The respective precedence rules and associativities of the operators used guarantee that the version absent any parentheses is equivalent to this explicitly parenthesized version:
(($a > $b) ? $x : $y) = $result;This is equivalent to the if-else version:
if ($a > $b) { $x = $result; } else { $y = $result; } PHP[edit]A simple PHP implementation is this:
$abs = $value >= 0 ? $value : -$value;Unlike most other programming languages, the conditional operator in PHP is left associative rather than right associative. Thus, given a value of T for arg, the PHP code in the following example would yield the value horse instead of train as one might expect:[15]