# Ternary operator expression

This is a discussion on Ternary operator expression within the C Programming forums, part of the General Programming Boards category; Hi, How this expression will be evaluated??? help me out Code: ((a>b)?((a>c)?a:c):((b>c)?b:c))...

1. ## Ternary operator expression

Hi,

How this expression will be evaluated??? help me out

Code:
`((a>b)?((a>c)?a:c):((b>c)?b:c))`

2. Originally Posted by rits
How this expression will be evaluated?
Quickly.

If you want to know what the expression does, analyse it yourself following what you know of the ternary operator.

3. the ?: operator is directly related to if..else statements. convert one to the other and you know how it works.
Code:
```// ((a>b)?((a>c)?a:c):((b>c)?b:c))
if (a > b)
{
if (a > c)
a;
else
c;
}
else
{
if (b > c)
b;
else
c;
}```

4. Thanks Meldreth very clear explanation...

5. It's worth noting that the ternary operator evaluates to a value, unlike if-else statements; so, for example, you can do something like this . . .
Code:
`sign = (number < 0 ? -1 : 1);`
Then sign is assigned the value -1 if number is negative, and +1 otherwise.

6. According to my limited thinking thats also if-else. if number is less than 0 sign is -1 otherwise 1

7. Originally Posted by rits
According to my limited thinking thats also if-else. if number is less than 0 sign is -1 otherwise 1
Yes, what dwks was trying to say is that the use of the ternary operator is slightly different from an if (although it has the same effect).
You can not do:
Code:
`x = if(a < b) a; else b;`
That will not compile.
You could do:
Code:
`if (a < b) x = a; else x = b;`
or you can use the ternary form:
Code:
`x = (a < b)?a:b;`
The latter comes in very handy if you have a long expression:
If-statements:
Code:
```if (a < b)
x = 3.6 * y + 9.6 *b;
else
x = 3.6 * y + 9.6 * a;```
would be a bit easier on the hands typing and the eyes reading it like this:
Code:
`   x = 3.6 *y + 9.6 * (a < b)?b:a;`
Note that there are situations when this is RIGHT, and other times when it is wrong. It may be better to have a temporary variable:
Code:
```double bigger = a;
if (a < b)
bigger = b;
x = 3.6 * y + 9.6 * bigger;```

--
Mats

8. The conditional evaluation is a compact way of expressing an if-else.

9. As I tried to say, the conditional operator is pretty much the same thing as an if-else statement. However, the ternary operator evaluates to a value, whereas an if-else construct does not. Whether you use this value is up to you.

You can always convert a ternary operator into an if-else, but it's not quite as simple as Meldreth has made out if the value of the expression is used. That's all I was trying to say, and matsp has elaborated nicely where I was too lazy to.

10. Hey buddies thanks to all of you