views:

3164

answers:

14

What is the need for the conditional operator? Functionally it is redundant, since it implements an if-else construct. If the conditional operator is more efficient than the equivalent if-else assignment, why can't if-else be interpreted more efficiently by the compiler?

+30  A: 

The ternary operator is a syntactic and readability convenience, not a performance shortcut. People are split on the merits of it for conditionals of varying complexity, but for short conditions, it can be useful to have a one-line expression.

John Feminella
+5  A: 

Compactness and the ability to inline an if-then-else construct into an expression.

tvanfosson
+3  A: 

It's syntatic sugar and a handy shorthand for brief if/else blocks that only contain one statement. Functionally, both constructs should perform identically.

Dana the Sane
+8  A: 

There are a lot of things in C that aren't technically needed because they can be more or less easily implemented in terms of other things. Here is an incomplete list:

  1. while
  2. for
  3. functions
  4. structs

Imagine what your code would look like without these and you may find your answer. The ternary operator is a form of "syntactic sugar" that if used with care and skill makes writing and understanding code easier.

1800 INFORMATION
To continue the argument, we don't really need C at all because we can do everything necessary with assembler.
Ether
"Portability is for people who cannot write new programs." - Linus Torvalds
Chris Lutz
+60  A: 

In C, the real utility of it is that it's an expression instead of a statement; that is, you can have it on the RHS of a statement. So you can write certain things more concisely.

Charlie Martin
+1: good way to put it, this is a more generalized point which covers what I wrote and more :).
Evan Teran
This is THE point. It converts an if/else into an expression, NOT a statement. Somehow I suspect quite a few people here don't understand the difference(please refrain from commenting that YOU do, I'm not talking to you ;) ).
Darren Clark
@Charlie: +1. I mentioned this in mine, but it's good to make this an explicit point.
John Feminella
And, because of this feature, it is a great tool to make code more "functional" and less "procedural".
Charles Bretana
+2  A: 

ternary = simple form of if-else. It is available mostly for readability.

Alphaneo
+4  A: 

Sometimes the ternary operator is the best way to get the job done. In particular when you want the result of the ternary to be an l-value.

This is not a good example, but I'm drawing a blank on somethign better. One thing is certian, it is not often when you really need to use the ternary, although I still use it quite a bit.

const char* appTitle  = amDebugging ? "DEBUG App 1.0" : "App v 1.0";

One thing I would warn against though is stringing ternaries together. They become a real
problem at maintennance time:

int myVal = aIsTrue ? aVal : bIsTrue ? bVal : cIsTrue ? cVal : dVal;

EDIT: Here's a potentially better example. You can use the ternary operator to assign references & const values where you would otherwise need to write a function to handle it:

int getMyValue()
{
  if( myCondition )
    return 42;
  else
    return 314;
}

const int myValue = getMyValue();

...could become:

const int myValue = myCondition ? 42 : 314;

Which is better is a debatable question that I will choose not to debate.

John Dibling
who ever would do that needs beaten=)
Matt Davison
I agree about the flogging, but I found that oddly readable. :)Surely on in test example with alphabetically aligned variables.
Darren Clark
Yeah, it gets real nasty when you start putting things in parenthesis.
John Dibling
Even one use can lead to bugs. Case in point: your release version will have the title "DEBUG App 1.0".
Michael Myers
+12  A: 

It's crucial for code obfuscation, like this:

Look->       See?!

No
:(
Oh, well
);
Artelius
Note: to make the above code compile, just add struct{int See;}*Look;int No,Oh,well;int main(){ /* above code goes in here*/ }
Artelius
+25  A: 

Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const correctness in a compact way.

Basically something like this:

const int n = (x != 0) ? 10 : 20;

so basically n is a const whose initial value is dependent on a condition statement. The easiest alternative is to make n not a const, this would allow an ordinary if to initialize it. But if you want it to be const, it cannot be done with an ordinary if. The best substitute you could make would be to use a helper function like this:

int f(int x) {
    if(x != 0) { return 10; } else { return 20; }
}

const int n = f(x);

but the ternary if version is far more compact and arguably more readable.

Evan Teran
Well, const *did* come along about, oh, 25 years after the conditional operator. That is a cute trick though.
Charlie Martin
+4  A: 

Since no one has mentioned this yet, about the only way to get smart printf statements is to use the ternary operator:

printf("%d item%s", count, count > 1 ? "s\n" : "\n");

Caveat: There are some differences in operator precedence when you move from C to C++ and may be surprised by the subtle bug(s) that arise thereof.

dirkgently
+4  A: 

The fact that the ternary operator is an expression, not a statement, allows it to be used in macro expansions for function-like macros that are used as part of an expression. Const may not have been part of original C, but the macro pre-processor goes way back.

One place where I've seen it used is in an array package that used macros for bound-checked array accesses. The syntax for a checked reference was something like aref(arrayname, type, index), where arrayname was actually a pointer to a struct that included the array bounds and an unsigned char array for the data, type was the actual type of the data, and index was the index. The expansion of this was quite hairy (and I'm not going to do it from memory), but it used some ternary operators to do the bound checking.

You can't do this as a function call in C because of the need for polymorphism of the returned object. So a macro was needed to do the type casting in the expression. In C++ you could do this as a templated overloaded function call (probably for operator[]), but C doesn't have such features.

dewtell
+1  A: 

Real programmers use the ternary operator.

Max Lybbert
A: 

The same as

if(0)
do();


if(0)
{
do();
}
Arabcoder
A: 

In some programming languages, if-else is an expression and evaluates to a value

def correct = true;
def answer = if (correct) "Yes" else "No";

so that there is no need for a conditional expression.

Helper Method