# Nested Ternary Operators in C

Page 1 of 1

## 4 Replies - 996 Views - Last Post: 16 March 2015 - 04:18 AMRate 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=372159&amp;s=2f95b8478893ce3d04b7cb1052b4ea09&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Promisek3u

Reputation: 0
• Posts: 16
• Joined: 23-January 15

# Nested Ternary Operators in C

Posted 15 March 2015 - 05:21 PM

Hello, I'm trying to solve this problem here:

http://i.imgur.com/V7IXUGn.png

It tells me the hint of using the ternary operator twice.

I understand that ternary operators are basically:

if (condition is true) ? then (this happens): else (this happens);

But the problem has two consecutive if statements. So far I have this:

```y = x != 0 ? a > b ? y = a/x:
y = b/x:

a > b ? y = a/0.000001:
y = b/0.000001;

```

Would that work?

Is This A Good Question/Topic? 0

## Replies To: Nested Ternary Operators in C

### #2 baavgai

• Dreaming Coder

Reputation: 6966
• Posts: 14,572
• Joined: 16-October 07

## Re: Nested Ternary Operators in C

Posted 15 March 2015 - 05:33 PM

Promisek3u, on 15 March 2015 - 08:21 PM, said:

if (condition is true) ? then (this happens): else (this happens);

Not quite. Rather, it's "condition ? return_this_value_if_true : return_this_value_if_false."

So, something like this is valid:
```y = (a > B)/> ? a : b;

```

### #3 Promisek3u

Reputation: 0
• Posts: 16
• Joined: 23-January 15

## Re: Nested Ternary Operators in C

Posted 15 March 2015 - 05:57 PM

I'm still having trouble trying to implement the code. What happens when there are two conditions in a row?

Like, the first condition is x != 0, and it is followed by the second condition of a > b.

I don't understand the formatting of that.

### #4 Promisek3u

Reputation: 0
• Posts: 16
• Joined: 23-January 15

## Re: Nested Ternary Operators in C

Posted 15 March 2015 - 06:13 PM

Nevermind, thank you for the help and I solved it! :

```y = x != 0 ?
(a > b ? a/x: b/x):
(a > b ? a/0.000001: b/0.000001);

```

The return values helped!

### #5 baavgai

• Dreaming Coder

Reputation: 6966
• Posts: 14,572
• Joined: 16-October 07

## Re: Nested Ternary Operators in C

Posted 16 March 2015 - 04:18 AM

Excellent.

Since the divisor is the same, you could also do:
```y = x != 0 ?
(a > b ? a : b ) / x:
(a > b ? a : b ) / 0.000001);

```

Note that this still uses three expressions. However, it points your closer to the solution requested, that only uses two.

Good luck.

This post has been edited by baavgai: 16 March 2015 - 04:20 AM
Reason for edit:: bloody b tag thingy