Adam Johns
Adam Johns

Reputation: 36343

Ternary operator with nothing in 'if' condition

What does the following code do?

return obj ? : [NSNull null];

From my understanding of ternary operations it would be equivalent to:

if (!obj)
    return [NSNull null];

But what gets returned if (obj)? Does it fall through to still return [NSNull null]?

Upvotes: 0

Views: 308

Answers (2)

Fogmeister
Fogmeister

Reputation: 77631

The code...

return foo ? : bar;

Will return the same value as...

return foo ? foo : bar;

The difference is that the first method only inspects the foo value once.

It is better to use the first in several cases.

For instance, creating an object...

// this would create two objects, one to check and the other to return
return [MyObject objectWithSomeParam:param] ? [MyObject objectWithSomeParam:param] : bar;

or running an expensive function...

// the expensive function here is run twice
return [self someExpensiveFunction] ? [self someExpensiveFunction] : bar;

Both of these would benefit from using

return foo ?: bar;

Essentially, if the validation object is the same as the return object for true then use the shortened version.

Upvotes: 3

Daniel Hepper
Daniel Hepper

Reputation: 29967

If obj is True, obj is returned.

return obj ? : [NSNull null];

is equivalent to:

id x = obj;
if (x) {
    return x;
else {
    return [NSNull null];
}

As long as obj has no side effects it is logically equivalent to:

return obj ? obj : [NSNull null]

Upvotes: 3

Related Questions