ternary vs if

In what situations would you use either one?

And is there a differents the ternary:
1
2

z = (x > y) ? z : y;


looks the exact same as the if:
1
2
3
4
5
6
7
8
9
if (x>y)
{
    x=y
}
else
{
    x=z
}
    




I'm new, so I'm certain I'm missing something, but why have to functions that do the same thing? or are they supposed to be used for specific task?
For simple one liner if-else statement we can use the ternary operator.

z = (x > y) ? z : y;

is equivalent to

if (x > y) {
z = z;
} else {
z = y;
}
uh.... I know.... it looks like you just quoted me... i'm asking what is the difference, not "how do you use ternary's"...

Or I could ask is there a right and wrong time to use either?
Last edited on
you had it backwards in your original post:

 
x = (condition) ? (value_if_true) : (value_if_false);


In your OP, you seemed to think the false value was first (or in any event, the ternary code you wrote doesn't match the if/else code you wrote).


Anyway that's a symptom of one of the biggest reasons not to use the ternary operator: clarity.

Ternary is nice for shortcutting code where if/else would be too verbose, but it can make code a little harder to follow.

As for performance tradeoffs, there usually aren't any. Ternary will be the same as if/else in many cases (it probably will even compile to the same code a lot of time). Really the only reason to use one or the other is stylistic / clarity related.

Personally, I don't use the ternary operator very often.
oic lol yeah i meant to make them match up I wasn't gonna a z at all, but did to make it more readable.

Anyway that's the reason I was wondering, I like the way if/else looks and it's easy (for thenewguy) to understand. I was just wondering so that somewhere down the road i didn't hit any big issues. Thanks you both. :)
Personally for me, I want to save typing strokes so I uses ternary operator for simple one-liner statements. I guess I am influenced by Perl one-liner code culture.

In terms of statement execution performance I think both should be the same with modern machines.
If you have something that can be neatly summed up in a ternary operator, then it makes sense. But how often do situations like that really come up? In my experience they're not very common.

Also... nested ternaries are evil.
Topic archived. No new replies allowed.