# Ternary Operator ? :

• (2 Pages)
• 1
• 2

## 21 Replies - 2540 Views - Last Post: 31 May 2009 - 10:49 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=107560&amp;s=91b8cc3501b8563bdc8e2c6330d345f5&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 IngeniousHax

• |>|20-514<|{3|2

Reputation: 78
• Posts: 1,353
• Joined: 28-March 09

# Ternary Operator ? :

Posted 29 May 2009 - 12:10 AM

```#include <iostream>

using namespace std;

int main() {
int x;
for(x = 0; x <= 15; x++)
x == 15 ? printf("it hit 15\n") : printf("still not 15:: #%d\n", x);
return 0;
}

```

Is it bad practice to use the Unary operator ? : ?? because to me, it just seems like you had a bagillion lines of code, it would be unusually difficult to find an error in a line like this.

Is This A Good Question/Topic? 0

## Replies To: Ternary Operator ? :

### #2 NickDMax

Reputation: 2235
• Posts: 9,216
• Joined: 18-February 07

## Re: Ternary Operator ? :

Posted 29 May 2009 - 12:32 AM

As used yes that is a bad practice. The ?: operator is NOT a substitute for if-else.

### #3 IngeniousHax

• |>|20-514<|{3|2

Reputation: 78
• Posts: 1,353
• Joined: 28-March 09

## Re: Ternary Operator ? :

Posted 29 May 2009 - 12:51 AM

Ok, Do you have an example or maybe a code snippet I could scout to see how it is truly used?

### #4 janotte

• code > sword

Reputation: 988
• Posts: 5,135
• Joined: 28-September 06

## Re: Ternary Operator ? :

Posted 29 May 2009 - 04:33 AM

NickDMax, on 28 May, 2009 - 11:32 PM, said:

As used yes that is a bad practice. The ?: operator is NOT a substitute for if-else.

I'm with IngeniousHax.

If "The ?: operator is NOT a substitute for if-else." then what is it for?

You can't leave us dangling like that.
The public demands to know

---------------
http://en.wikipedia.org/wiki/%3F:

EDIT
Ah ha - I see the conversation was expanded in this thread
http://www.dreaminco...topic107332.htm
and the dangling ended thusly.

This post has been edited by janotte: 29 May 2009 - 04:42 AM

### #5 baavgai

• Dreaming Coder

Reputation: 5334
• Posts: 11,907
• Joined: 16-October 07

## Re: Ternary Operator ? :

Posted 29 May 2009 - 04:48 AM

IngeniousHax, on 29 May, 2009 - 01:51 AM, said:

Ok, Do you have an example or maybe a code snippet I could scout to see how it is truly used?

Well, the point is to return a value based on a condition.

So, something like this:
```#include <iostream>

int main() {
for(int x = 0; x <= 15; x++)
printf("%d is %s.\n", x, (x%2==0) ? "even" : "odd");
return 0;
}

```

Rule of thumb: if you're not using the return value, it's probably wrong. If it's more that one one, don't bother.

### #6 born2c0de

• printf("I'm a %XR",195936478);

Reputation: 176
• Posts: 4,667
• Joined: 26-November 04

## Re: Ternary Operator ? :

Posted 29 May 2009 - 05:33 AM

Quote

Is it bad practice to use the Unary operator ? : ??

What???
Of course not, as long as you use it right.
If used correctly the ternary conditional operator can even improve code readability.

### #7 NickDMax

Reputation: 2235
• Posts: 9,216
• Joined: 18-February 07

## Re: Ternary Operator ? :

Posted 29 May 2009 - 06:40 AM

The conditional operator is meant to allow conditional expressions -- one should not be using void functions as expressions.

So for example one might use something like this:
```int daysInMonth(int month, int year) {
static const monthDays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
return monthDays[month] + month == 2 ? ((year % 16 || (year % 4 && !(year % 100)) ? 1, 0) : 0;
}
```

Or when calculating the value of split functions:
```int f(double x) { return (x < 0) ? x :  sin( 5.0 * x ) / 5.0; }
```

especially if you need that value inside of a larger calculation.

Avoiding division by zero: y = (x != 0) ? sin (x)/x : 0;

Conditional expressions come in handy to avoid an ugly if-else in cout expressions:
cout << "Take one down pass it around, " << x << ((x == 1) ? " bottle " : " bottles ") << " of beer on the wall!" << endl;

The point is that the conditional operator gives an expression -- it has a value. If you don't need that value, then you should be using a if-else structure.

### #8 IngeniousHax

• |>|20-514<|{3|2

Reputation: 78
• Posts: 1,353
• Joined: 28-March 09

## Re: Ternary Operator ? :

Posted 29 May 2009 - 01:18 PM

IDK, still seems like a substitute for an if-else statement. and in fact, I think it would even be more efficient to use it to call functions and return values. Just seems easier, while I can see how if it used in-properly it can cause a dilemma. But I suppose that is why everyone has a coding style and preference all their own and no ones code is ever the same.

### #9 NickDMax

Reputation: 2235
• Posts: 9,216
• Joined: 18-February 07

## Re: Ternary Operator ? :

Posted 29 May 2009 - 01:55 PM

The conditional operator comes from functional programming and is therefore a duck out of water in C/C++ -- so many programmers really detest it. However with other functional components making their way into C++ perhaps its use will increase.

Quote

IDK, still seems like a substitute for an if-else statement.

In some ways it is -- but it greatly simplifies code since you don't need to declare intermediate values. It takes a while to sink in I suppose but the key to understanding the conditional operator is understanding that it is an expression.

### #10 IngeniousHax

• |>|20-514<|{3|2

Reputation: 78
• Posts: 1,353
• Joined: 28-March 09

## Re: Ternary Operator ? :

Posted 29 May 2009 - 02:07 PM

YEah, perhaps one day it will click. But for now it just presents itself as a substitute of an if-else statement. Perhaps next semester when I take Intermediate C++ I will understand it more.

### #11 IngeniousHax

• |>|20-514<|{3|2

Reputation: 78
• Posts: 1,353
• Joined: 28-March 09

## Re: Ternary Operator ? :

Posted 31 May 2009 - 06:45 PM

I realise a few people had said that the
``` ? :
```
ternary operator was not a replacement for an if-else statement, and while many of those people are for more advanced adn knowledgeable than I am. I was just flipping through my Intro to C++ book and on the front index, where they give all kinds of quick references, it has this::
```Form:
Expression ? expression : expression
Example:
x = a < b ? a : b;
The statement above works like <-note that is is bigger than the other words:
if (a < b)
x = a;
else
x = b

```

So the context inwhich I was using it was technically bad practice, however it is a substitute for an if-else statement.

### #12 jcmaster2

Reputation: 2
• Posts: 183
• Joined: 27-April 09

## Re: Ternary Operator ? :

Posted 31 May 2009 - 08:25 PM

Quote

So the context inwhich I was using it was technically bad practice, however it is a substitute for an if-else statement.

I would agree in fact

An assignment of the value of a conditional expression to a variable (x = y ? z : w;) can always be
replaced by:

a switch statement with assignment statements for its case statements.

one or more ifs with else clauses and assignment statements for its true and false clauses.

one or more nested while loops with assignments for the bodies of the loops.

### #13 NickDMax

Reputation: 2235
• Posts: 9,216
• Joined: 18-February 07

## Re: Ternary Operator ? :

Posted 31 May 2009 - 08:28 PM

Just because it can be used as one does not mean that it IS one or that it should be used as such. Every time you see ?: you can rewrite the statement using if-else, but you should not go around willy-nilly replacing if-else with ?:

The ?: operator make an expression. Its purpose is to be used inside of expressions. Lets look at some other expression a + b, a * b, a << b. These are expressions, they have a calculated value.

we can replace: x = a + b with:
x = a;
x += b;

but should you?

C/C++ allow you to do many things that you should not. If you really WANT to use ?: to replace if-else you can do that. On the other hand if you choose not to ever use ?: and to only use if-else you would be in good company.

Keep in mind as you look at ?: that if-else CAN NOT have a value, and ?: CAN -- that is the difference.

### #14 jcmaster2

Reputation: 2
• Posts: 183
• Joined: 27-April 09

## Re: Ternary Operator ? :

Posted 31 May 2009 - 09:18 PM

Quote

Just because it can be used as one does not mean that it IS one or that it should be used as such. Every time you see ?: you can rewrite the statement using if-else, but you should not go around willy-nilly replacing if-else with ?:

Agreed but as mentioned it can be used as an alternative...

another example

x= x++ + ++x;

is technically undefined in C/C++ but not Java/C#- but people still do it anyway...

### #15 NickDMax

Reputation: 2235
• Posts: 9,216
• Joined: 18-February 07

## Re: Ternary Operator ? :

Posted 31 May 2009 - 09:32 PM

Anyone who puts x++ + ++x in real code should be shot even if the language allows it.