Are there any languages in which the ternary operator can be used to modify code structure? - ternary-operator

I am curious to know if there are any languages in which the ternary operator can be used to modify code structure at run time. Such as:
boolean bool = true;
// Addition method - can add 2 or 3 integers.
add(5,10 bool ? ) : ,15);
I would assume that if this exists anywhere, both the if and else statements of the ternary must be acceptable at compile-time.

No, because
such a language would be a syntactical nightmare
the intended effect can easily be produced by using
result = bool ? add( 5, 10 ) : add( 5, 10, 15 ) # both expressions evaluated?
result = add( 5, 10, bool ? 0 : 15 ) # maybe nil, empty, or nix instead of 0
the standard if of the language


To ternary or not to ternary? [closed]

I'm personally an advocate of the ternary operator: () ? : ; I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.
What are your feelings on it? What interesting code have you seen using it?
Use it for simple expressions only:
int a = (b > 10) ? c : d;
Don't chain or nest ternary operators as it hard to read and confusing:
int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8;
Moreover, when using ternary operator, consider formatting the code in a way that improve readability:
int a = (b > 10) ? some_value
: another_value;
It makes debugging slightly more difficult since you can not place breakpoints on each of the sub expressions. I use it rarely.
I love them, especially in type-safe languages.
I don't see how this:
int count = (condition) ? 1 : 0;
is any harder than this:
int count;
if (condition)
count = 1;
count = 0;
edit -
I'd argue that ternary operators make everything less complex and more neat than the alternative.
Chained I'm fine with - nested, not so much.
I tend to use them more in C simply b/c they're an if statement that has value, so it cuts down on unnecessary repetition or variables:
x = (y < 100) ? "dog" :
(y < 150) ? "cat" :
(y < 300) ? "bar" : "baz";
rather than
if (y < 100) { x = "dog"; }
else if (y < 150) { x = "cat"; }
else if (y < 300) { x = "bar"; }
else { x = "baz"; }
In assignments like this, I find it's less to refactor, and clearer.
When I'm working in ruby on the other hand, I'm more likely to use if...else...end because it's an expression too.
x = if (y < 100) then "dog"
elif (y < 150) then "cat"
elif (y < 300) then "bar"
else "baz"
(although, admittedly, for something this simple, I might just use the ternary operator anyway).
The Ternary ?: operator is merely a functional equivalent of the procedural if construct. So as long as you are not using nested ?: expressions, the arguments for/against the functional representation of any operation applies here. But nesting ternary operations can result in code that is downright confusing (exercise for the reader: try writing a parser that will handle nested ternary conditionals and you will appreciate their complexity).
But there are plenty of situations where conservative use of the ?: operator can result in code that is actually easier to read than otherwise. For example:
int compareTo(Object object) {
if((isLessThan(object) && reverseOrder) || (isGreaterThan(object) && !reverseOrder)) {
return 1;
if((isLessThan(object) && !reverseOrder) || (isGreaterThan(object) && reverseOrder)) {
return -1;
return 0;
Now compare that with this:
int compareTo(Object object) {
return reverseOrder ? 1 : -1;
return reverseOrder ? -1 : 1;
return 0;
As the code is more compact it there is less syntactic noise, and by using the ternary operator judiciously (that is only in relation with the reverseOrder property) the end result isn't particularly terse.
It's a question of style, really; the subconscious rules I tend to follow are:
Only evaluate 1 expression - so foo = (bar > baz) ? true : false, but NOT foo = (bar > baz && lotto && someArray.Contains(someValue)) ? true : false
If I'm using it for display logic, e.g. <%= (foo) ? "Yes" : "No" %>
Only really use it for assignment; never flow logic (so never (foo) ? FooIsTrue(foo) : FooIsALie(foo) ) Flow logic in ternary is itself a lie, ignore that last point.
I like it because it's concise and elegant for simple assignment operations.
Like so many opinion questions, the answer is inevitably: it depends
For something like:
return x ? "Yes" : "No";
I think that is much more concise (and quicker for me to parse) than:
if (x) {
return "Yes";
} else {
return "No";
Now if your conditional expression is complex, then the ternary operation is not a good choice. Something like:
x && y && z >= 10 && s.Length == 0 || !foo
is not a good candidate for the ternary operator.
As an aside, if you are a C programmer, GCC actually has an extension that allows you to exclude the if-true portion of the ternary, like this:
/* 'y' is a char * */
const char *x = y ? : "Not set";
Which will set x to y assuming y is not NULL. Good stuff.
In my mind, it only makes sense to use the ternary operator in cases where an expression is needed.
In other cases, it seems like the ternary operator decreases clarity.
By the measure of cyclomatic complexity, the use of if statements or the ternary operator are equivalent. So by that measure, the answer is no, the complexity would be exactly the same as before.
By other measures such as readability, maintainability, and DRY (Don't-Repeat-Yourself), either choice may prove better than the other.
I use it quite often in places where I'm constrained to work in a constructor - for example, the new .NET 3.5 LINQ to XML constructs - to define default values when an optional parameter is null.
Contrived example:
var e = new XElement("Something",
param == null ? new XElement("Value", "Default")
: new XElement("Value", param.ToString())
or (thanks asterite)
var e = new XElement("Something",
new XElement("Value",
param == null ? "Default"
: param.ToString()
No matter whether you use the ternary operator or not, making sure your code is readable is the important thing. Any construct can be made unreadable.
I use the ternary operator where ever I can, unless it makes the code extremely hard to read, but then that's usually just an indication that my code could use a little refactoring.
It always puzzles me how some people think the ternary operator is a "hidden" feature or is somewhat mysterious. It's one of the first things I learnt when I start programming in C, and I don't think it decreases readability at all. It's a natural part of the language.
I agree with jmulder: it shouldn't be used in place of a if, but it has its place for return expression or inside an expression:
echo "Result: " + n + " meter" + (n != 1 ? "s" : "");
return a == null ? "null" : a;
The former is just an example, a better i18n support of plural should be used!
If you're using the ternary operator for a simple conditional assignment I think it's fine. I've seen it (ab)used to control program flow without even making an assignment, and I think that should be avoided. Use an if statement in these cases.
(Hack of the day)
#define IF(x) x ?
#define ELSE :
Then you can do if-then-else as expression:
int b = IF(condition1) res1
ELSE IF(condition2) res2
ELSE IF(conditions3) res3
ELSE res4;
I think the ternary operator should be used when needed. It is obviously a very subjective choice, but I find that a simple expression (specially as a return expression) is much clearer than a full test. Example in C/C++:
return (a>0)?a:0;
Compared to:
if(a>0) return a;
else return 0;
You also have the case where the solution is between the ternary operator and creating a function. For example in Python:
l = [ i if i > 0 else 0 for i in lst ]
The alternative is:
def cap(value):
if value > 0:
return value
return 0
l = [ cap(i) for i in lst ]
It is needed enough that in Python (as an example), such an idiom could be seen regularly:
l = [ ((i>0 and [i]) or [0])[0] for i in lst ]
this line uses properties of the logical operators in Python: they are lazy and returns the last value computed if it is equal to the final state.
I like 'em. I don't know why, but I feel very cool when I use the ternary expression.
I've seen such beasts like (it was actually much worse since it was isValidDate and checked month and day as well, but I couldn't be bothered trying to remember the whole thing):
isLeapYear =
((yyyy % 400) == 0)
? 1
: ((yyyy % 100) == 0)
? 0
: ((yyyy % 4) == 0)
? 1
: 0;
where, plainly, a series of if-statements would have been better (although this one's still better than the macro version I once saw).
I don't mind it for small things like:
reportedAge = (isFemale && (Age >= 21)) ? 21 + (Age - 21) / 3 : Age;
or even slightly tricky things like:
printf ("Deleted %d file%s\n", n, (n == 1) ? "" : "s");
I like using the operator in debug code to print error values so I don't have to look them up all the time. Usually I do this for debug prints that aren't going to remain once I'm done developing.
int result = do_something();
if( result != 0 )
debug_printf("Error while doing something, code %x (%s)\n", result,
result == 7 ? "ERROR_YES" :
result == 8 ? "ERROR_NO" :
result == 9 ? "ERROR_FILE_NOT_FOUND" :
I almost never use the ternary operator because whenever I DO use it, it always makes me think a lot more than I have to later when I try to maintain it.
I like to avoid verbosity, but when it makes the code a lot easier to pick up, I will go for the verbosity.
String name = firstName;
if (middleName != null) {
name += " " + middleName;
name += " " + lastName;
Now, that is a bit verbose, but I find it a lot more readable than:
String name = firstName + (middleName == null ? "" : " " + middleName)
+ " " + lastName;
String name = firstName;
name += (middleName == null ? "" : " " + middleName);
name += " " + lastName;
It just seems to compress too much information into too little space, without making it clear what's going on. Everytime I see ternary operator used, I have always found an alternative that seemed much easier to read... then again, that is an extremely subjective opinion, so if you and your colleagues find ternary very readable, go for it.
Well, the syntax for it is horrid. I find functional ifs very useful, and often makes code more readable.
I would suggest making a macro to make it more readable, but I'm sure someone can come up with a horrible edge case (as there always is with CPP).
Only when:
$var = (simple > test ? simple_result_1 : simple_result_2);
As others have pointed out they are nice for short simple conditions. I especially like them for defaults (kind of like the || and or usage in javascript and python), e.g.
int repCount = pRepCountIn ? *pRepCountIn : defaultRepCount;
Another common use is to initialize a reference in C++. Since references have to be declared and initialized in the same statement you can't use an if statement.
SomeType& ref = pInput ? *pInput : somethingElse;
I treat ternary operators a lot like GOTO. They have their place, but they are something which you should usually avoid to make the code easier to understand.
I recently saw a variation on ternary operators (well, sort of) that make the standard "() ? :" variant seem to be a paragon of clarity:
var Result = [CaseIfFalse, CaseIfTrue][(boolean expression)]
or, to give a more tangible example:
var Name = ['Jane', 'John'][Gender == 'm'];
Mind you, this is Javascript, so things like that might not be possible in other languages (thankfully).
For simple if cases, I like to use it. Actually it's much easier to read/code for instance as parameters for functions or things like that. Also to avoid the new line I like to keep with all my if/else.
Neseting it would be a big NO-NO in my book.
So, resuming, for a single if/else I'll use the ternary operator. For other cases a regular if/else if/else (or switch)
I typically use in things like this:
I like Groovy's special case of the ternary operator, called the Elvis operator: ?:
expr ?: default
This code evaluates to expr if it's not null, and default if it is. Technically it's not really a ternary operator, but it's definitely related to it and saves a lot of time/typing.
For simple tasks like assigning a different value depending on a condition they're great. I wouldn't use them when there are longer expressions depending on the condition tho.
A so many answers have said, it depends. I find that if the ternary comparison is not visible in a quick scan down the code, then it should not be used.
As a side issue, I might also note that its very existence is actually a bit of an anomoly due to the fact that in C, comparison testing is a statement. In Icon, the if construct (like most of Icon) is actually an expression. So you can do things like:
x[if y > 5 then 5 else y] := "Y"
... which I find much more readable than a ternery comparison operator. :-)
There was a discussion recently about the possibility of adding the ?: operator to Icon, but several people correctly pointed out that there was absolutely no need because of the way if works.
Which means that if you could do that in C (or any of the other languages that have the ternery operator), then you wouldn't, in fact, need the ternery operator at all.
If you and your workmates understand what they do and they aren't created in massive groups I think they make the code less complex and easier to read because there is simply less code.
The only time i think ternary operators make code harder to understand is when you have more than 3 or 4 in one line. Most people don't remember that they are right based precedence and when you have a stack of them it makes reading the code a nightmare.

Need advice on the Swift while statement

The following code got compilation error:
var a : Int = 0
var b : Int = 3
var sum : Int = 0
while (sum = a+b) < 2 {
The error message is:
Cannot invoke '<' with an argument list of type '((()),
How to solve this problem? (Of course I can put sum assignment statement out side the while statement. But this is not convenient. Any other advice? Thanks
In many other languages, including C and Objective-C, sum = a+b would return the value of sum, so it could be compared.
In Swift, this doesn't work. This was done intentionally to avoid a common programmer error. From The Swift Programming Language:
Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator (=) does not return a value, to prevent it from being mistakenly used when the equal to operator (==) is intended.
Since the assignment operator does not return a value, it can't be compared with another value.
It is not possible to overload the default assignment operator (=), but you could create a new operator or overload one of the compound operators to add this functionality. However, this would be unintuitive to future readers of your code, so you may want to simply move the assignment to a separate line.
In most languages, assignments propagate their value -- that is, when you call
sum = a + b
the new value of sum is available for another part of the expression:
doubleSum = (sum = a + b) * 2
Swift doesn't work that way -- the value of sum isn't available after the assignment, so it can't be compared in your while statement. From Apple's documentation:
This feature prevents the assignment operator (=) from being used by
accident when the equal to operator (==) is actually intended. By
making if x = y invalid, Swift helps you to avoid these kinds of
errors in your code.
The other answers explain why your code won't compile. Here is how you can clean it up without calculating sum in the while loop (I'm assuming you want to be able to reassign what sum's getter is, elsewhere.):
var a = 0, b = 3
var getSum = { a + b }
var sum: Int { return getSum() }
while sum < 2 {
...and if you're okay with invoking sum with parentheses:
var a = 0, b = 3
var sum = { a + b }
while sum() < 2 {
You can rewrite it as a for loop, although you'll have to repeat the assignment and addition:
for sum = a+b; sum < 2; sum = a+b {

How to Implement the Ternary Operator in the DLR

I am implementing a language interpreter in C# using the DLR, and I'm having some troubles with the ternary operator. At this point, I have basic function declarations/calls implemented, like so:
F := (x) -> x + 1
F(1) # returns 2
I've not had a problem with a function body being a sequence of expressions -- the value of the last expression is always returned, and I've made sure all cases in the interpreter return at least something as a side effect. I'm now trying to implement the ternary operator (? :). The Expression tree I'm rendering looks like this:
work = Expression.IfThenElse(
Expression.IsTrue(Expression.Convert(work, typeof(Boolean))),
where trueExp and falseExp are both valid expressions.
The problem seems to be that the IfThenElse expression does not return a value, so basically even though trueExp and falseExp are building expression trees, the end result of the IfThenElse expression is always null. Short of making a Runtime function and explicitly calling it, is there a way to implement the ternary operator using the DLR? (ie: an Expression. that does the IfThenElse and returns the actual values in the true and false clauses?)
What I hope to parse is something like:
F := (x) -> (x = 1) ? 4 : 5
F(1) #4
F(2) #5
But right now this always returns null when compiled into a program, because of the problem outlined above.
I'd appreciate any help, this is quite vexing!
Expression.IfThenElse is an if (...) ... else ...; construct, not the ternary operator.
The ternary operator is Expression.Condition

Concept of true,false logically and numerically?

I was asked this question in an interview! I just wanted to know what the right answer to this is. I told that logically the concept is represented by bool data type(C#).A variable of bool data type can have true or false value and can be used as a conditional check condition.Numerically, 1 represents true and 0 represents false in most programming languages.I don't know what else to add or what is the distinction between the two.Any comments will be greatly appreciated.
In C# (unlike some other languages) booleans are not integers and are not convertible to integers:
int x = true; // Error - Cannot implicitly convert type 'bool' to 'int'
As a result it doesn't make sense to say that true is equal to 1 in C#. At an implementation level the value true might be stored internally as the value 1, but this is a detail specific to that implementation, not a feature of C# itself.
If you want to convert a boolean to the value 0 or 1 you can do this:
int x = isFoo ? 1 : 0;

When and where to use ternary operator? [closed]

I often read ternary operator(? : ) in books,but I am not clear the best practice of it.
What is the advantages and disadvantages or best practice of it?
The ternary operator ? : represents an if-then-else construct, except that it actually returns a value. So instead of:
if ( condition )
x = expression1;
x = expression2;
You can write:
x = (condition) ? (expression1) : (expression2);
In C, C++, Java, etc., you cannot write:
x = if (condition) (expression1) else (expression2);
Some languages, like Ruby, do allow a form like that, however, since statements in Ruby always return a value, and the value of a block is the value returned by the last statement in a block.
You may use the operator as
int nNum1 = 10, nNum2 = 20, nMax = ( nNum1 > nNum2 ) ? nNum1 : nNum2
It is shorthand for simple if-else comparisons, where a variable is assigned based on the result of the comparison.