Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the conditional (ternary) operator?

I've always wondered how to write the "A ? B : C" syntax in a C++ compatible language.

I think it works something like: (Pseudo code)

If A > B    C = A Else    C = B 

Will any veteran C++ programmer please help me out?

like image 549
Robin Rodricks Avatar asked Dec 25 '08 16:12

Robin Rodricks


People also ask

What is a conditional ternary operator in C?

Ternary Operators in C/C++The operators, which require three operands to act upon, are known as ternary operators. It can be represented by “ ? : ”. It is also known as conditional operator. The operator improves the performance and reduces the line of code.

What is the use of ternary operator explain with example?

The ternary operator is an operator that exists in some programming languages, which takes three operands rather than the typical one or two that most operators use. It provides a way to shorten a simple if else block. For example, consider the below JavaScript code. alert(msg);


2 Answers

It works like this:

(condition) ? true-clause : false-clause 

It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in VB, for example).

For example:

bool Three = SOME_VALUE; int x = Three ? 3 : 0; 

is the same as

bool Three = SOME_VALUE; int x; if (Three)     x = 3; else     x = 0; 
like image 181
lc. Avatar answered Oct 02 '22 16:10

lc.


It works like this:

expression ? trueValue : falseValue 

Which basically means that if expression evaluates to true, trueValue will be returned or executed, and falseValue will be returned or evaluated if not.

Remember that trueValue and falseValue will only be evaluated and executed if the expression is true or false, respectively. This behavior is called short circuiting.

like image 40
magcius Avatar answered Oct 02 '22 14:10

magcius