Brandon Hohn
Brandon Hohn

Reputation: 1

Having Trouble Using A Ternary Statement

I'm making a binary tree and this is my insert function; it works perfectly:

if(newData < data){
    if(left) left->insert(newData);
    else left = new Node(newData);
}else{
    if(right) right->insert(newData);
    else right = new Node(newData);
}

I wanted to transform this into this:

if(newData < data)
    left ? left->insert(newData) : left = new Node(newData);
else
    right = right ? right : new Node(newData);

However, I'm getting this error: Left operand to ? is void, but right operand is of type 'Node *'

I understand this is because there's something to do with having the ternary statement be the same on both sides, but I was wondering if anyone knew a possible solution for this short of just using an if/else statement so I can learn the limitations behind the code.

Thanks!

Upvotes: 0

Views: 134

Answers (3)

Robert Andrzejuk
Robert Andrzejuk

Reputation: 5222

The ternary operator is an expression.

It is not an if else statement.

It returns a result - at runtime, so its type has to be determined during compilation.

It can only be one type at a time, so in effect both branches have to return a result of the same type

In your branches, the types of the expressions are different. This is the reason of the error.

Upvotes: 1

Brandon Hohn
Brandon Hohn

Reputation: 1

Thanks to everyone that helped so incredibly quickly! To all of you who mentioned the readability of the new code as opposed to the original, I totally understand that I should keep it as it is in the beginning. Thanks to everyone posting about the nature of the statement!

For anyone ends up wondering what the solution was, for fun, Eljay nailed it:

((newData < data) ? left : right) =
      (newData < data) ? (left ? (( void )left->insert(newData), left)
                               : new Node(newData))
                       : (right ? (( void )right->insert(newData), right)
                                : new Node(newData));

Thank you all so much! I'm extremely impressed by how awesome the StackOverflow community is!

Upvotes: 0

jf_
jf_

Reputation: 3479

The ternary operator ? is not just a shorthand for if, but requires three expressions: condition ? exprIfTrue : exprIfFalse

If the condition evaluates to true, the whole constuct evaluates to exprIfTrue, if false to exprIfFalse. In contrast to if it can be used in an assignment, hence the two expressions have to have a type that conforms to the variable the result is assigned to. ? can better be compared to the if in functional languages.

Upvotes: 0

Related Questions