user9061340
user9061340

Reputation:

Can we use ternary operator within an if statement?

My teacher says we can't use a ternary operator within an if statement as it's an alternative for it... Can anyone please tell me if we can use ternary operators within an if statement in c++?

Upvotes: 0

Views: 7002

Answers (3)

developer123
developer123

Reputation: 91

I know this question is old. However I came accross another useful example I used recently in my code:

if ( by_start ? (tmp_segment1->start > tmp_segment2->start) : 
                (tmp_segment1->end > tmp_segment2->end) )
{
   ...
}

It's basically about sorting a list by the element's member variable start or end. By using the ternary operator inside the if the code becomes significantly smaller but it is still readable.

Upvotes: -3

Rene
Rene

Reputation: 2466

The basic answer is: Yes, you can.
As @Bathsheba already pointed out: It may not always make sense.

A more sensible example might be something like this:

if (use_locking ? readLocked() : readUnlocked())
{
   ...
}

Upvotes: 6

Bathsheba
Bathsheba

Reputation: 234875

Yes you can.

A ternary conditional operator is an expression with type inferred from the type of the final two arguments. And expressions can be used as the conditional in an if statement.

An example is the perversion

if (unemployed ? false : true)

which stands in for

if (!unemployed)

Naturally, whether or not it's a good thing to do depends on the context.

Upvotes: 4

Related Questions