I\'ve always wondered how to write the \"A ? B : C\"
syntax in a C++ compatible language.
I think it works something like: (Pseudo
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;
In c++ there's no actual if part of this. It's called the ternary operator. It's used like this: <boolean statement> ? <result if true> : <result if false>; For your example above it would look like this:
C = A > B ? A : B;
This article on wikipedia also discusses it: http://en.wikipedia.org/wiki/Ternary_operation
I assume you mean stuff like a = b ? c : d, where b is the condition, c is the value when b is true, and d is the value when b is false.
simply you can write this as
C=(A>B)?A:B;
THIS IS SAME AS:
if(A>B)
C=A;
else
C=B;
This is called a "Ternary operator", and the ?
and :
are another way of writing an if-else statement.
Look at the "Example #1" in this Codepen, and un-comment it... you'll notice what it does.
Now comment "Example #1", un-comment "Example #2", and see what happens. The code does the exact same thing... but this time with only 5 lines of code. Notice how whatever appears before the ?
sign is the if
(conditional), and whatever comes AFTER the :
is the thing to be executed.
But what if you have a conditional that requires an "else-if" (with more than 2 possible outcomes) like the one in the Codepen's "Example #3" (which adds the possibility of the user writing a specific wrong answer)? Then the ternary operator might not be as useful, but you can certainly concatenate several conditions with the ternary operator, like on this ES6 fizzbuzz example.
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.