Question

Is there a difference between using the '?:' conditional and the simple 'if-then-else' statement? Is it simply another way to do it, or does it actually use less space/take less time to read than 'if' statements?

Example:

If statement:

if (item1.isEqualToString:@"2") //If statement
    [self doSomething];
else
    [self doSomethingElse];

item1.isEqualToString:@"2" ? [self doSomething] : [self doSomethingElse]; //'?:' statement
Was it helpful?

Solution

Yes, there is a difference.

Semantically an if/else statement means

if (condition)
  statements
else
  statements

while a the ternary conditional is

condition ? expression : expression

so you can assign the result of a ?: operator to something while you can't do it with an if statement. Actually the ?: operator is an expression itself so you can nest it inside other expressions, even other ?: operators.

The ?: is also type checked, this

condition ? [self methodThatReturnsVoid] : [self methodThatReturnsInt]

raises an error since the result type could change according to condition.

OTHER TIPS

There is a difference, as Jack suggests. You could rewrite the ?: operator as:

ExpressionType temp;
if (condition) {
    temp = trueExpression;
}
else {
    temp = falseExpression;
}
lvalue = temp;  // (Where "lvalue" refers to the receiver of the resulting value)

As to efficiency, several machine instruction sets have versions of ?: implemented in hardware for simple cases, but not for more complex cases (where they would use something akin to the above), so it's hard to say which is more efficient when.

The main advantage of the ?: operator is that it allows a conditional operation to be embedded within an expression vs having to break up the expression with if/else, and this can make for conceptually (and visually) simpler code, even though the actual machine complexity is not significantly (if at all) reduced.

To append to the good answers provided by Jack and Hot Licks, the determination of which to use is driven partly by necessity and partly by style. For example, ?: typically reduces redundancy, which can result in simpler, shorter code that's easier to read and easier to maintain - no risk of updating one half of the if..else and forgetting the other. e.g.

int result = SomeFunction(arg1, arg2, arg3, (someBool ? arg4a : arg4b));

vs

int result = -1;
if (someBool) {
    result = SomeFunction(arg1, arg2, arg3, arg4a);
} else {
    result = SomeFunction(arg1, arg2, arg3, arg4b);
}

This is a concise example for brevity, but you could imagine that with real argument names and surrounding complexity, it could be easy to come back months from now and modify the second call to SomeFunction without realising the other exists, let alone should be modified too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top