?:


In computer programming, ?: 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, inline if , or ternary if. An expression 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".
It originally comes from CPL, in which equivalent syntax for e1 ? e2 : e3 was e1e2, e3.
Although many ternary operators are possible, the conditional operator is so common, and other ternary operators so rare, that the conditional operator is commonly referred to as the ternary operator.

Variations

The detailed semantics of "the" ternary operator as well as its syntax differs significantly from language to language.
A top level distinction from one language to another is whether the expressions permit side effects and whether the language provides short-circuit evaluation semantics, whereby only the selected expression is evaluated.
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.
Furthermore, if no order is guaranteed, a distinction exists about whether the result is then classified as indeterminate or undefined.
If the language does not permit side-effects in expressions, 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.
For these reasons, in some languages the statement form variable = condition ? expr1 : expr2; can have subtly different semantics than the block conditional form if else .
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" : , but PHP in particular is notoriously left-associative, and evaluates as follows: ? "two" : "many", which is rarely what any programmer expects.

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.
However, in this idiom it is almost certain that the entire tuple expression will evaluate prior to the subscript expression, so there will be no short-circuit semantics.
Nested ternaries can be simulated as c 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

?: is used as follows:
The 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 have the same type, which determines the type of the whole expression. The importance of this type-checking lies in the operator's most common use—in conditional assignment statements. In this usage it appears as an expression on the right side of an assignment statement, as follows:
The ?: operator is similar to the way conditional expressions work in functional programming languages, like Scheme, ML, and Haskell, since if-then-else forms an expression instead of a statement in those languages.

Usage

The conditional operator's most common usage is to make a terse simple conditional assignment statement. For example, if we wish to implement some C code to change a shop's normal opening hours from 9 o'clock to 12 o'clock on Sundays, we may use

int opening_time = ? 12 : 9;

instead of the more verbose

int opening_time;
if
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 is an expression in the first place e.g. the Scheme expression is equivalent in semantics to the C expression. This is also the case in many imperative languages, starting with ALGOL where it is possible to write, or Smalltalk or Ruby.
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, regardless of whether or not its result will be used. Programmers should consult their programming language specifications or test the ternary operator to determine whether or not the language will evaluate both expressions in this way. If it does, and this is not the desired behaviour, then an if-then-else statement should be used.

ActionScript 3


condition ? value_if_true : value_if_false

Ada

The 2012 edition of Ada has introduced conditional expressions, as part of an enlarged set of expressions including quantified expressions and expression functions. The Rationale for Ada 2012 states motives for Ada not having had them before, as well as motives for now adding them, such as to support "contracts".
Pay_per_Hour := ;
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 68

Both ALGOL 68's choice clauses provide the coder with a choice of either the "bold" syntax or the "brief" form.
if condition then statements fi
"brief" form:
if condition1 then statements elif condition2 then statements fi
"brief" form:

APL

With the following syntax, both expressions are evaluated :

result ← value_if_true ⊣⍣ condition ⊢ value_if_false

This alternative syntax provides short-circuit evaluation:

result ← ⍬

AWK


result = condition ? value_if_true : value_if_false

Bash

A true ternary operator only exists for arithmetic expressions:

)

For strings there only exist workarounds, like e.g.:

result=$

C

A traditional if-else construct in C, Java and JavaScript is written:

if
else

This can be rewritten as the following statement:

result = a > b ? x : y;

As in the if-else construct only one of the expressions 'x' and 'y' is evaluated. This is significant if the evaluation of 'x' or 'y' has side effects.ISO.IEC 9899:1999 6.5.15.4
The behaviour is undefined if an attempt is made to use the result of the conditional operator as an lvalue.
A GNU 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 if x is an expression, it is evaluated only once. The difference is significant if evaluating the expression has side effects. This shorthand form is sometimes known as the Elvis operator in other languages.

C#

In C#, if condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. As with Java only one of two expressions is ever evaluated.
//condition ? first_expression : second_expression;
static double sinc

C++

Unlike in C, the precedence of the ?: operator in C++ is the same as that of the assignment operator, and it can return an lvalue. This means that expressions like q ? a : b = c and = c are both legal and are parsed differently, the former being equivalent to q ? a : .
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:

  1. include
  2. include
  3. include
int main

In this case there is no possibility of using an if-else statement in place of the ?: operator.
Furthermore, the conditional operator can yield an lvalue, i.e. a value to which another value can be assigned. Consider the following example:

  1. include
int main

NOTE:In C++ and other various languages, Ternary operators like a>b>c are also possible but are very rare.
In this example, if the boolean expression argc > 1 yields the value true in line 5, the value 1 is assigned to the variable a, otherwise, it is assigned to b.

[CFML]


result = randRange ? "heads" : "tails";

Roughly 50% of the time the randRange expression will return 1 or 0 ; meaning result will take the value "heads" or "tails" respectively.

Lucee, Railo, and ColdFusion 11-specific

, 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_null

Example:

result = f ?: "default";
// where...
function f
writeOutput;

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

Example of using this operator in CoffeeScript:
if 1 is 2 then "true value" else "false value"
Returns "false value".

Common Lisp

Assignment using a conditional expression in Common Lisp:


Alternative form:


)

Crystal

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

Delphi

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: Integer;
function IfThen: Int64;
function IfThen: UInt64;
function IfThen: Single;
function IfThen: Double;
function IfThen: Extended;

Using the System.StrUtils library

function IfThen: string;

Usage example:

function GetOpeningTime: Integer;
begin

Result := IfThen or ;
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.

FORTH

Since FORTH is a stack-oriented language, and any expression can leave a value on the stack, all IF/ELSE/THEN sequences can generate values:


This word takes 1 parameter on the stack, and if that number is odd, leaves 22. If it's even, 42 is left on the stack.

Fortran

With the additions to the code in the 1995 release, the ternary operator was added to the Fortran compiler as the intrinsic function merge:

variable = merge

Note that both x and y are evaluated before the results of one or the other are returned from the function.

Go

There is no ternary if in Go, so use of the full if statement is always required.

Haskell

The built-in if-then-else syntax is inline: the expression

if predicate then expr1 else expr2

has type

Bool -> a -> a -> a

The base library also provides the function Data.Bool.bool:

bool :: a -> a -> Bool -> a

In both cases, no special treatment is needed to ensure that only the selected expression is evaluated, since Haskell is non-strict by default. This also means an operator can be defined that, when used in combination with the $ operator, functions exactly like ?: in most languages:

:: Bool -> a -> a -> a
pred x y = if pred then x else y
infix 1 ?
-- example :
arg = 'A'
vehicle = arg 'B' ? "boat" $
arg 'A' ? "airplane" $
arg 'T' ? "train" $
"car"

However, it is more idiomatic to use

-- example :
arg = 'A'
vehicle | arg 'B' = "boat"
| arg 'A' = "airplane"
| arg 'T' = "train"
| otherwise = "car"

Java

In Java this expression evaluates to:
If foo is selected, assign selected foo to bar. If not, assign baz to bar.

Object bar = foo.isSelected ? foo : baz;

Note that Java, in a manner similar to C#, only evaluates the used expression and will not evaluate the unused expression.

Julia

In Julia, "Note that the spaces around ? and : are mandatory: an expression like a?b:c is not a valid ternary expression."

JavaScript

The conditional operator in JavaScript is similar to that of C++ and Java, 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 : instead of = c.

var timeout = settings ! null ? settings.timeout : 1000;

Just like C# and Java, the expression will only be evaluated if, and only if, the expression is the matching one for the condition given; the other expression will not be evaluated.

Kotlin

Note: Kotlin does not include a traditional ternary operator, instead favoring the use of conditional expressions.
As the complexity of your conditional statement grows, you might consider replacing your if-else expression with a when expression, as shown in the following example:
In Kotlin, the conditional operator works as follows: If the expression to the left of ?: is not null, the Elvis operator returns it, otherwise it returns the expression to the right. Note that the right-hand side expression is evaluated only if the left-hand side is null.

val name = node.getOptionalName ?: "default name"

Lua

Lua does not have a traditional conditional operator. However, the short-circuit behaviour of its "and" and "or" operators allows the emulation of this behaviour:

-- 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 behaviour if ignored.

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 to the ternary operator:

SELECT AS "Conditional_Example"
FROM tab;

This can be expanded to several conditionals:

SELECT AS "Conditional_Example"
FROM tab;

MySQL

In addition to the standard CASE expression, MySQL provides an IF function as an extension:

IF;

SQL Server

In addition to the standard CASE expression, SQL Server provides an IIF function:

IIF

Oracle SQL

In addition to the standard CASE expression, Oracle has a variadic functional counterpart which operates similarly to a switch statement and can be used to emulate the conditional operator when testing for equality.

-- General syntax takes case-result pairs, comparing against an expression, followed by a fall-back result:
DECODE
-- We can emulate the conditional operator by just selecting one case:
DECODE

The DECODE function is, today, deprecated in favour of the standard CASE expression. This can be used in both Oracle SQL queries as well as PL/SQL blocks, whereas decode can only be used in the former.

Perl

A traditional if-else construct in Perl is written:

if else

Rewritten to use the conditional operator:

$result = $a > $b ? $x : $y;

The precedence of the conditional operator in perl is the same as in C, not as in C++. This is conveniently of higher precedence than a comma operator but lower than the precedence of most operators used in expressions within the ternary operator, so the use of parentheses is rarely required.
Its associativity matches that of C and C++, not that of PHP. Unlike C but like C++, perl allows the use of the conditional expression as an L-value; for example:

$a > $b ? $x : $y = $result;

will assign $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:

= $result;

This is equivalent to the if-else version:

if else

PHP

A simple PHP implementation is this:

$abs = $value >= 0 ? $value : -$value;

Due to an unfortunate design of the language grammar, the conditional operator in PHP is left associative in contrast to other languages, 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:

$arg = "T";
$vehicle = ? 'bus' :
? 'airplane' :
? 'train' :
? 'car' :
? 'horse' :
'feet' );
echo $vehicle;

The reason is that nesting two conditional operators produces an oversized condition with the last two options as its branches: c1 ? o1 : c2 ? o2 : o3 is really. This is acknowledged and will probably not change. To avoid this, nested parenthesis are needed, as in this example:

$arg = "T";
$vehicle = $arg "B" ? "bus" :
);
echo $vehicle;

This will produce the result of train being printed to the output, analogous to a right associative conditional operator.

PHP 5.3

Since PHP 5.3 there is a short-hand of the conditional operator, sometimes referred to as the "Elvis Operator". The syntax for this short-hand is below:

$c = $a ?: $b; // equivalent to $c = $a ? $a : $b;

Python

Though it had been delayed for several years by disagreements over syntax, an operator for a conditional expression in Python was approved as and was added to the 2.5 release in September 2006. Python's conditional operator differs from the common ?: operator in the order of its operands. The general form is:
result = x if a > b else y
This form invites considering x as the normal value and y as an exceptional case. One can use the syntax
result =
as a workaround for code that also needs to run under Python versions before 2.5. Note that operands are lazily evaluated, it is possible to remove the lambdas and function calls but the operands will be eagerly evaluated which isn't consistent with the conditional operator of most other languages, e.g. by indexing a tuple,
result =
or using an explicitly constructed dictionary:
result =
A less reliable but simpler to read alternative is to abuse the and and or operators and write
result = and x or y
but this code would break if x could be a "falsy" value as the expression would return y instead of the x.
A possible workaround is to make x and y lists or tuples, so they are never falsy, and then grab the first element of the resulting sequence as in the following
result =
or
result = and or )
Note, when wrapping Python's conditional construct into a utility function, the unalterably eager nature of the more intuitive language construct for side-effect functions

>>> func = lambda b, a1, a2 :
>>> def true:
... print "true"
... return "truly"
>>> def false:
... print "false"
... return "falsely"
>>> func, false)
true
false
'truly'
>>> func, false)
true
false
'falsely'

similar results from
func = lambda b,a1,a2: a1 if b else a2
func = lambda b, a1, a2:
func = lambda b, a1, a2:

as the correct call would be

>>> func
true
'truly'
>>> func
false
'falsely'

however the Python 2.5 construct is safer; calling the construct directly works more intuitively

>>> true if True else false
true
'truly'
>>> true if False else false
false
'falsely'

clearly the reason being that in the case of func, false) the functions are called when sent as parameters rather than when returned from func

R

The traditional if-else construct in R is:

if else

If there is only one statement in each block, braces can be omitted, like in C:

if
x <- "true"
else
x <- "false"

The code above can be written in the following non-standard condensed way:

x <- if "true" else "false"

There exists also the function ifelse that allows rewriting the expression above as:

x <- ifelse

The ifelse function is automatically vectorized. For instance:

> ifelse
"true" "false"

Raku

uses a doubled ?? symbol instead of single ?
and a doubled !! symbol instead of :

$result = $a > $b ?? $x !! $y;

Ruby

Example of using this operator in Ruby:
1 2 ? "true value" : "false value"
Returns "false value".
A traditional if-else construct in Ruby is written:

if a > b
result = x
else
result = y
end

This could also be written as:

result = if a > b
x
else
y
end

These can be rewritten as the following statement:

result = a > b ? x : y

Rust

Being an expression-oriented programming language, rust's existing if expr1 else expr2 syntax can behave as the traditional ?:; ternary operator does. Earlier versions of the language did have the ?:; operator but it was removed due to duplication with if.
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 else ;

This could also be written as:

let y = if x 5 else

Note that curly braces are mandatory in Rust conditional expressions.
You could also use a match expression:

let y = match x ;

Scheme

Same as in Common Lisp. Every expression has a value. Thus the builtin if can be used:

)
...)

Smalltalk

Every expression has a value. Thus ifTrue:ifFalse: can be used:

x := 5.
y := ifTrue: ifFalse:.

Swift

The ternary conditional operator of Swift is written in the usual way of the C tradition, and is used within expressions.

let result = a > b ? a : b

Tcl

Example of using this operator in Tcl:

set x 5
set y

TestStand

In a expression, if condition is true, the first expression is evaluated and becomes the output of the conditional operation; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.
condition ? first_expression : second_expression
For example:
RunState.Root.Parameters.TestSocket.Index 3 ? Locals.UUTIndex = 3 : Locals.UUTIndex = 0
Sets the UUTIndex local variable to 3 if TestSocket.Index is 3, otherwise it sets UUTIndex to 0.
Similar to other languages, first_expression and second_expression do not need to be autonomous expressions, allowing the operator to be used for variable assignment:
Locals.UUTIndex =

Verilog

is technically a hardware description language, not a programming language though the semantics of both are very similar. It uses the ?: syntax for the ternary operator.

// using blocking assignment
wire out;
assign out = sel ? a : b;

This is equivalent to the more verbose Verilog code:

// using blocking assignment
wire out;
if // sel is 1, not 0, x or z
assign out = a;
else if // sel is 0, x or z
assign out = b;
else // sel is x or z
assign out = ; // a and b are compared bit by bit, and return for each bit
// an x if bits are different, and the bit value if the same

Visual Basic

doesn't use ?: per se, but has a very similar implementation of this shorthand if...else statement. Using the first example provided in this article, it can do:

' variable = IIf
Dim opening_time As Integer = IIf

In the above example, IIf is a ternary function, but not a ternary operator. As a function, the values of all three portions are evaluated before the function call occurs. This imposed limitations, and in Visual Basic.Net 9.0, released with Visual Studio 2008, an actual conditional operator was introduced, using the If keyword instead of IIf. This allows the following example code to work:

Dim name As String = If

Using IIf, person.Name would be evaluated even if person is null, causing an exception. With a true short-circuiting conditional operator, person.Name is not evaluated unless person is not null.
Visual Basic Version 9 has added the operator If in addition to the existing IIf function that existed previously. As a true operator, it does not have the side effects and potential inefficiencies of the IIf function.
The syntaxes of the tokens are similar: If vs IIf. As mentioned above, the function call has significant disadvantages, because the sub-expressions must all be evaluated, according to Visual Basic's evaluation strategy for function calls and the result will always be of type variant or object. The Ifoperator however does not suffer from these problems as it supports conditional evaluation and determines the type of the expression based on the types of its operands.

Result type

Clearly the type of the result of the ?: operator must be in some sense the type unification of the types of its second and third operands. In C this is accomplished for numeric types by arithmetic promotion; since C does not have a type hierarchy for pointer types, pointer operands may only be used if they are of the same type or one is void or NULL. It is undefined behaviour to mix pointer and integral or incompatible pointer types; thus
number = spell_out_numbers ? "forty-two" : 42;
will result in a compile-time error in most compilers.

?: in style guidelines

Conditional operators are widely used and can be useful in certain circumstances to avoid the use of an if statement, either because the extra verbiage would be too lengthy or because the syntactic context does not permit a statement. For example:
#define MAX >) ? : )
or

for
c_patterns.ShowWindow;

Initialization

An important use of the conditional operator is in allowing a single initialization statement, rather than multiple initialization statements. In many cases this also allows single assignment and for an identifier to be a constant.
The simplest benefit is avoiding duplicating the variable name, as in Python:

x = 'foo' if b else 'bar'

instead of:

if b:
x = 'foo'
else:
x = 'bar'

More importantly, in languages with block scope, such as C++, the blocks of an if/else statement creates new scopes, and thus variables must be declared before the if/else statement, as:

std::string s;
if
s = "foo";
else
s = "bar";

Use of the conditional operator simplifies this:

std::string s = b ? "foo" : "bar";

Further, since initialization is now part of the declaration, rather than a separate statement, the identifier can be a constant :

const std::string s = b ? "foo" : "bar";

Case selectors

When properly formatted, the conditional operator can be used to write simple and coherent case selectors. For example:

vehicle = arg 'B' ? bus :
arg 'A' ? airplane :
arg 'T' ? train :
arg 'C' ? car :
arg 'H' ? horse :
feet;

Appropriate use of the conditional operator in a variable assignment context reduces the probability of a bug from a faulty assignment as the assigned variable is stated just once as opposed to multiple times.

Programming languages without the conditional operator

The following are examples of notable general-purpose programming languages that don't provide a conditional operator: