views:

594

answers:

14

I'm currently a student in college learning, and for the most part enjoying, the wonderful world of programming. I'm lucky enough to know about SO, and have a friend who's been in the game since he was fairly young, so I get exposed to some things that haven't come up in class.

One such thing was the conditional ?: operator. I had no idea it existed until a few days ago. I'm not sure how I feel about using it on my current project, though. I work in an environment of almost entirely non-programmers. The program I'm currently translating from VB6 to C# was written by a mechanical engineer (and breaks some basic programming tenets, like unnecessary use of gotos). I was hoping somebody would be able to give me the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

Conditional ?: Operator

  • Shorter and more concise when dealing with direct value comparisons and assignments
  • Doesn't seem to be as flexible as the if/else construct

Standard If/Else

  • Can be applied to more situations (such as function calls)
  • Often are unnecessarily long

Readability seems to vary for each depending on the statement. For a little while after first being exposed to the ?: operator, it took me some time to digest exactly how it worked. Would you recommend using it wherever possible, or sticking to if/else given the nature of the generally-non-programming environment I'm in?

+2  A: 

I find it particularly helpful when doing web development if I want to set a variable to a value sent in the request if it is defined or to some default value if it is not.

wshato
+1 default values in web dev is an excellent example a good place to use the ternary operator
Byron Whitlock
the null coalescing operator (`??`) would be more adequate in that case...
Thomas Levesque
+15  A: 

I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

Good example:

int result = Check() ? 1 : 0;

Bad example:

int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
Dan Tao
Good call, but for the record, that's "concision."
mquander
@mquander, you sure about that? http://www.merriam-webster.com/dictionary/concise
Byron Whitlock
Hmm, go figure; perhaps it can just as well be either.
mquander
@mquander: I figured that was a clever joke. If so, kudos ;) Or should I say, "kds."
Dan Tao
I always start out with a simple one and make it more complex over time until it is completely unreadable.
Jouke van der Maas
Readability in the second example could easily be rectified with better formatting. But, as the OP is recommending, it comes down to readability and terseness versus verbosity.
Nathan Ernst
+1  A: 

If I'm setting a value and I know it will always be one line of code to do so, I typically use the ternary (conditional) operator. If there's a chance my code and logic will change in the future, I use an if/else as it's more clear to other programmers.

Of further interest to you may be the ?? operator.

drharris
+1  A: 

The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if is a statement, it cannot return a value.

Gabe
+1  A: 

One thing to recognize when using the ternary operator that it is an expression not a statement.

In functional languages like scheme the distinction doesn't exists:

(if (> a b) a b)

Conditional ?: Operator "Doesn't seem to be as flexible as the if/else construct"

In functional languages it is.

When programming in imperative languages I apply the ternary operator in situations where I typically would use expressions (assignment, conditional statements, etc).

Ken Struys
A: 

I'd recommend limiting the use of the ternary(?:) operator to simple single line assignment if/else logic. Something resembling this pattern:

if(<boolCondition>) {
    <variable> = <value>;
}
else {
    <variable> = <anotherValue>;
}

Could be easily converted to:

<variable> = <boolCondition> ? <value> : <anotherValue>;

I would avoid using the ternary operator in situations that require if/else if/else, nested if/else, or if/else branch logic that results in the evaluation of multiple lines. Applying the ternary operator in these situations would likely result in unreadable, confusing, and unmanageable code. Hope this helps.

HOCA
A: 

The conditional operator is great for short conditions, like this:

varA = boolB ? valC : valD;

I use it occasionally because it takes less time to write something that way... unfortunately, this branching can sometimes be missed by another developer browsing over your code. Plus, code isn't usually that short, so I usually help readability by putting the ? and : on separate lines, like this:

doSomeStuffToSomething(shouldSomethingBeDone()
    ? getTheThingThatNeedsStuffDone()
    : getTheOtherThingThatNeedsStuffDone());

However, the big advantage to using if/else blocks (and why I prefer them) is that it's easier to come in later and add some additional logic to the branch,

if (shouldSomethingBeDone()) {
    doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
    doSomeAdditionalStuff();
} else {
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}

or add another condition:

if (shouldSomethingBeDone()) {
    doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
    doSomeAdditionalStuff();
} else if (shouldThisOtherThingBeDone()){
    doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}

So, in the end, it's about convenience for you now (shorter to use :?) vs. convenience for you (and others) later. It's a judgment call... but like all other code-formatting issues, the only real rule is to be consistent, and be visually courteous to those who have to maintain (or grade!) your code.

(all code eye-compiled)

iandisme
A: 

There is some performance benefit of using the the ? operator in eg. MS Visual C++, but this is a really a compiler specific thing. The compiler can actually optimize out the conditional branch in some cases.

Cornelius Scarabeus
A: 

The scenario I most find myself using it is for defaulting values and especially in returns

return someIndex < maxIndex ? someIndex : maxIndex;

Those are really the only places I find it nice, but for them I do.

Though if you're looking for a boolean this might sometimes look like an appropriate thing to do:

bool hey = whatever < whatever_else ? true : false;

Because it's so easy to read and understand, but that idea should always be tossed for the more obvious:

bool hey = (whatever < whatever_else);
Jimmy Hoffa
A: 

If you need multiple branches on the same condition, use an if:

if (A == 6)
  f(1, 2, 3);
else
  f(4, 5, 6);

If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:

f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );

Also, you can use the ternary operator in initialization.

const int i = (A == 6)? 1 : 4;

Doing that with if is very messy:

int i_temp;
if (A == 6)
   i_temp = 1;
else
   i_temp = 4;
const int i = i_temp;

You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.

Ben Voigt
+4  A: 

I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.

if (a > 0)
    answer = compute(a, b, c, d, e);
else
    answer = compute(-a, b, c, d, e);

With a ternary operator, this could be accomplished with the following.

answer = compute(a > 0 ? a : -a, b, c, d, e); 
Ryan Bright
personally I would do `aVal = a > 0 ? a : -a; answer = compute(aVal,b,c,d,e);` Especially if `b`, `c`, `d` and `e` required treatment too.
glowcoder
Why use a conditional at all in this example? Just get Abs(a) and call compute() once.
Ash
Yeah, I didn't create the best example. :)
Ryan Bright
To a newbie, that does not look equivalent. Wouldn't it need to be answer = compute(a > 0 ? a, b, c, d, e : -a, b, c, d, e); ?
pbreitenbach
A: 

The ternary operator can be included within an rvalue, whereas an if-then-else cannot; on the other hand, an if-then-else can execute loops and other statements, whereas the ternary operator can only execute (possibly void) rvalues.

On a related note, the && and || operators allow some execution patterns which are harder to implement with if-then-else. For example, if one has several functions to call and wishes to execute a piece of code if any of them fail, it can be done nicely using the && operator. Doing it without that operator will either require redundant code, a goto, or an extra flag variable.

supercat
+2  A: 

This is pretty much covered by the other answers, but "it's an expression" doesn't really explain why that is so useful...

In languages like C++, you can define constants using them. This is not possible with a conventional if/then statement because the value of a const all has to be assigned within that single statement:

const int speed = (shiftKeyDown) ? 10 : 1;

is not the same as:

const int speed;  
if (shifKeyDown)  
    speed = 10;    // error - can't assign to a const  
else  
    speed = 1;     // error  

In a similar way you can embed a tertiary expression in other code. As well as making the source code more compact (and in some cases more readable as a result) it can also make the generated machine code more compact and efficient:

MoveCar((shiftKeyDown) ? 10 : 1);

...may generate less code than having to call the same method twice:

if (shiftKeyDown)
    MoveCar(10);
else
    MoveCar(1);

Of course, it's also a more convenient and concise form (less typing, less repetition, and can reduce the chance of errors if you have to duplicate chunks of code in an if/else). In clean "common pattern" cases like this:

object thing = (reference == null) ? null : reference.Thing;

... it is simply faster to read/parse/understand (once you're used to it) than the long-winded if/else equivalent, so it can help you to 'grok' code faster.

Jason Williams
A: 

A really cool usage is:

x = foo ? 1 :
    bar ? 2 :
    baz ? 3 :
          4;
aib