C Ternary Operator Assignment 2

The latest version of this topic can be found at Conditional Operator: ? :.

Syntax

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows:

  • The first operand is implicitly converted to . It is evaluated and all side effects are completed before continuing.

  • If the first operand evaluates to true (1), the second operand is evaluated.

  • If the first operand evaluates to false (0), the third operand is evaluated.

The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression.

Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third operands:

  • If both operands are of the same type, the result is of that type.

  • If both operands are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Arithmetic Conversions) are performed to convert them to a common type.

  • If both operands are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type.

  • If both operands are of reference types, reference conversions are performed to convert them to a common type.

  • If both operands are of type void, the common type is type void.

  • If both operands are of the same user-defined type, the common type is that type.

  • If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.)

Any combinations of second and third operands not in the preceding list are illegal. The type of the result is the common type, and it is an l-value if both the second and third operands are of the same type and both are l-values.

If the types of the second and third operands are not identical, then complex type conversion rules, as specified in the C++ Standard, are invoked. These conversions may lead to unexpected behavior including construction and destruction of temporary objects. For this reason, we strongly advise you to either (1) avoid using user-defined types as operands with the conditional operator or (2) if you do use user-defined types, then explicitly cast each operand to a common type.

C++ Operators
C++ Built-in Operators, Precedence and Associativity
Conditional-Expression Operator

expression ? expression : expression
// expre_Expressions_with_the_Conditional_Operator.cpp // compile with: /EHsc // Demonstrate conditional operator #include <iostream> using namespace std; int main() { int i = 1, j = 2; cout << ( i > j ? i : j ) << " is greater." << endl; }

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the statement.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

condition ? expr1 : expr2

Parameters

An expression that evaluates to or .
,
Expressions with values of any type.

Description

If is , the operator returns the value of ; otherwise, it returns the value of .

A simple example to test whether or not you're old enough to legally drink alcohol in USA.

var age = 26; var canDrinkAlcohol = (age > 21) ? "True, over 21" : "False, under 21"; console.log(canDrinkAlcohol); // "True, over 21"

Another example is to display a different message based on the value of the variable, you could use this statement:

'The fee is ' + (isMember ? '$2.00' : '$10.00');

You can also assign variables depending on a ternary result:

var elvisLives = Math.PI > 4 ? 'Yep' : 'Nope';

Multiple ternary evaluations are also possible (note: the conditional operator is right associative):

var firstCheck = false, secondCheck = false, access = firstCheck ? 'Access denied' : secondCheck ? 'Access denied' : 'Access granted'; console.log(access); // logs "Access granted"

You can also use multiple conditions like in a multiple-conditions IF statement

var condition1 = true, condition2 = false, access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false"); console.log(access); // logs "true false"

Note: The parentheses are not required, and do not affect the functionality. They are there to help visualize how the outcome is processed.

You can also use ternary evaluations in free space in order to do different operations:

var stop = false, age = 16; age > 18 ? location.assign('continue.html') : stop = true;

You can also do more than one single operation per case, separating them with a comma, and enclosing them in parenthesis:

var stop = false, age = 23; age > 18 ? ( alert('OK, you can go.'), location.assign('continue.html') ) : ( stop = true, alert('Sorry, you are much too young!') );

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned.

var age = 16; var url = age > 18 ? ( alert('OK, you can go.'), // alert returns "undefined", but it will be ignored because // isn't the last comma-separated value of the parenthesis 'continue.html' // the value to be assigned if age > 18 ) : ( alert('You are much too young!'), alert('Sorry :-('), // etc. etc. 'stop.html' // the value to be assigned if !(age > 18) ); location.assign(url); // "stop.html"

Returning Ternary Statements

The ternary operator lends itself well to function returns that would otherwise require an  statement.

var func1 = function( .. ) { if (condition1) { return value1 } else { return value2 } } var func2 = function( .. ) { return condition1 ? value1 : value2 }

A common way of writing a function with a return value using legal drinking age in USA

function canDrinkAlcohol(age) {   return (age > 21) ? "True, over 21" : "False, under 21"; } var output = canDrinkAlcohol(26); console.log(output); // "True, over 21"

A good way to spot that the ternary will be a suitable replacement for an  statement is when the  keyword is used multiple times and is the only expression inside of the if block.

By breaking the ternary onto multiple lines and making use of extra whitespace, the ternary operator can be used to very cleanly replace a lengthy series of  statements. This provides a syntactically light way of expressing the same logic:

var func1 = function( .. ) { if (condition1) { return value1 } else if (condition2) { return value2 } else if (condition3) { return value3 } else { return value4 } } var func2 = function( .. ) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4 }

Specifications

Browser compatibility

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support Yes Yes1 Yes Yes Yes
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support Yes Yes Yes4 Yes Yes ?
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportFull support YesFull support YesFull support 1Full support YesFull support YesFull support YesFull support YesFull support YesFull support YesFull support 4Full support YesFull support Yes ? Full support Yes

Legend

Full support
Full support
Compatibility unknown
Compatibility unknown

See also

Document Tags and Contributors

 Contributors to this page:Clavicus, Kagerjay, wbamberg, fscholz, NWCalvank, Soupedenuit, Tombez, jameshkramer, Axngm, nmve, SphinxKnight, reoim, Sebastianz, dnapierata, teoli, OWaz, Delapouite, Havvy, fusionchess, Mrsonord, ethertank, Sheppy, Toutenrab, ArthurOgawa, hitautodestruct, Mgjbot, Ptak82, Dria

 Last updated by:Clavicus,

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *