Conditional operator

Last updated

The conditional operator is supported in many programming languages. This term usually refers to ?: as in C, C++, C#, and JavaScript. However, in Java, this term can also refer to && and ||.

Contents

&& and ||

In some programming languages, e.g. Java, the term conditional operator refers to short circuit boolean operators && and ||. The second expression is evaluated only when the first expression is not sufficient to determine the value of the whole expression. [1]

Difference from bitwise operator

& and | are bitwise operators that occur in many programming languages. The major difference is that bitwise operations operate on the individual bits of a binary numeral, whereas conditional operators operate on logical operations. Additionally, expressions before and after a bitwise operator are always evaluated.

if(expression1||expression2||expression3)

If expression 1 is true, expressions 2 and 3 are NOT checked.

if(expression1|expression2|expression3)

This checks expressions 2 and 3, even if expression 1 is true.

Short circuit operators can reduce run times by avoiding unnecessary calculations. They can also avoid Null Exceptions when expression 1 checks whether an object is valid.

Usage in Java

classConditionalDemo1{publicstaticvoidmain(String[]args){intvalue1=1;intvalue2=2;if((value1==1)&&(value2==2))System.out.println("value1 is 1 AND value2 is 2");if((value1==1)||(value2==1))System.out.println("value1 is 1 OR value2 is 1");}}

"?:"

In most programming languages, ?: is called the conditional operator. It is a type of ternary operator. However, ternary operator in most situations refers specifically to ?: because it is the only operator that takes three operands. [2]

By contrast, Python implements the ternary operator in the form of a condensed one-line if else statement [3] . For example:

x=10print('Even'ifx%2==0else'Odd')# Output:# Even

Regular usage of "?:"

?: is used in conditional expressions. Programmers can rewrite an if-then-else expression in a more concise way by using the conditional operator. [4]

Syntax

condition?expression1:expression2

condition: An expression which is evaluated as a boolean value.

expression 1, expression 2: Expressions with values of any type.

If the condition is evaluated to true, the expression 1 will be evaluated. If the condition is evaluated to false, the expression 2 will be evaluated.

It should be read as: "If condition is true, assign the value of expression 1 to result. Otherwise, assign the value of expression 2 to result."

Association property

The conditional operator is right-associative, meaning that operations are grouped from right to left. For example, an expression of the form a ? b : c ? d : e is evaluated as a ? b : (c ? d : e). [2]

Examples by languages

Java
classConditionalDemo2{publicstaticvoidmain(String[]args){intvalue1=1;intvalue2=2;intresult;booleansomeCondition=true;result=someCondition?value1:value2;System.out.println(result);}}

In this example, because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).

C++
#include<iostream>intmain(){intx=1;inty=2;std::cout<<(x>y?x:y)<<" is the greater of the two."<<std::endl;}

There are several rules that apply to the second and third operands in C++:

  • 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 Standard 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. [5]
C#
// condition ? first_expression : second_expression;staticdoublesinc(doublex){returnx!=0.0?Math.Sin(x)/x:1.0;}

There are several rules that apply to the second and third operands x and y in C#:

  • If x has type X and y has type Y:
  • If an implicit conversion exists from X to Y but not from Y to X, Y is the type of the conditional expression.
  • If an implicit conversion exists from Y to X but not from X to Y, X is the type of the conditional expression.
  • Otherwise, no expression type can be determined, and a compile-time error occurs.
  • If only one of x and y has a type, and both x and y are implicitly convertible to that type, that type is the type of the conditional expression.
  • Otherwise, no expression type can be determined, and a compile-time error occurs. [2]
JavaScript
varage=26;varbeverage=(age>=21)?"Beer":"Juice";console.log(beverage);// "Beer"

The conditional operator of JavaScript is compatible with the following browsers:

Chrome, Edge, Firefox (1), Internet Explorer, Opera, Safari, Android webview, Chrome for Android, Edge Mobile, Firefox for Android (4), Opera for Android, Safari on IOS, Samsung Internet, Node.js. [6]

Special usage in conditional chain

The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if ... else if ... else if ... else chain. [5]

Examples by languages

JavaScript
functionexample(){returncondition1?value1:condition2?value2:condition3?value3:value4;}// Equivalent to:functionexample(){if(condition1){returnvalue1;}elseif(condition2){returnvalue2;}elseif(condition3){returnvalue3;}else{returnvalue4;}}
C/C++
constdoublea=expression1?a1:expression2?a2:expression3?a3:/*otherwise*/a4;// Equivalent to:doublea;if(expression1)a=a1;elseif(expression2)a=a2;elseif(expression3)a=a3;else/*otherwise*/a=a4;

Special usage in assignment expression

the conditional operator can yield a L-value in C/C++ which can be assigned another value, but the vast majority of programmers consider this extremely poor style, if only because of the technique's obscurity. [7]

C/C++

((foo)?bar:baz)=frink;//equivalent to:if(foo)bar=frink;elsebaz=frink;

See also

Related Research Articles

In logic, mathematics, and computer science, arity is the number of arguments or operands taken by a function, operation or relation. In mathematics, arity may also be called rank, but this word can have many other meanings. In logic and philosophy, arity may also be called adicity and degree. In linguistics, it is usually named valency.

In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operations and directly supported by the processor. Most bitwise operations are presented as two-operand instructions where the result replaces one of the input operands.

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition . Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime. Conditional statements are the checkpoints in the programe that determines behaviour according to situation.

This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.

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, ternary if, or inline 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". The form a ? b : c is by far and large the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.

In computer science, the Boolean is a data type that has one of two possible values which is intended to represent the two truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century. The Boolean data type is primarily associated with conditional statements, which allow different actions by changing control flow depending on whether a programmer-specified Boolean condition evaluates to true or false. It is a special case of a more general logical data type—logic does not always need to be Boolean.

In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities.

The computer programming languages C and Pascal have similar times of origin, influences, and purposes. Both were used to design their own compilers early in their lifetimes. The original Pascal definition appeared in 1969 and a first compiler in 1970. The first version of C appeared in 1972.

In computer science, a Boolean expression is an expression used in programming languages that produces a Boolean value when evaluated. A Boolean value is either true or false. A Boolean expression may be composed of a combination of the Boolean constants true or false, Boolean-typed variables, Boolean-valued operators, and Boolean-valued functions.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

In computing, IIf is a function in several editions of the Visual Basic programming language and ColdFusion Markup Language (CFML), and on spreadsheets that returns the second or third parameter based on the evaluation of the first parameter. It is an example of a conditional expression, which is similar to a conditional statement.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#, PowerShell as of version 7.0.0, Perl as of version 5.10, Swift, and PHP 7.0.0. While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand. This behavior allows a default value to be defined for cases where a more specific value is not available.

Ateji PX is an object-oriented programming language extension for Java. It is intended to facilliate parallel computing on multi-core processors, GPU, Grid and Cloud.

In the C programming language, operations can be performed on a bit level using bitwise operators.

In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. This is identical to a short-circuit or with "last value" semantics. The notation of the Elvis operator was inspired by the ternary conditional operator, ? :, since the Elvis operator expression A ?: B is approximately equivalent to the ternary conditional A ? A : B.

A bitwise trie is a special form of trie where each node with its child-branches represents a bit sequence of one or more bits of a key. A bitwise trie with bitmap uses a bitmap to denote valid child branches.

References

  1. "Equality, Relational, and Conditional Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)". docs.oracle.com. Retrieved 2019-04-29.
  2. 1 2 3 BillWagner. "?: Operator - C# Reference". docs.microsoft.com. Retrieved 2019-04-29.
  3. "Python Ternary Operator". ioflood.com. Retrieved 2023-12-07.
  4. "The ? : operator in Java". www.cafeaulait.org. Retrieved 2019-04-29.
  5. 1 2 mikeblome. "Conditional Operator: ? :". docs.microsoft.com. Retrieved 2019-04-29.
  6. "Conditional (ternary) operator - JavaScript". developer.mozilla.org. Retrieved 2019-04-29.
  7. "Conditional Operator". wiki.c2.com. Retrieved 2019-04-29.