Is there any difference between "?:" And if statement in c lens?

Is there a difference between using the conditional expression "?:" And the simple expression "if-then-else"? Is this just another way of doing this, or is it actually using less space / takes less time to read than if statements?

Example:

If the instruction:

if (item1.isEqualToString:@"2") //If statement [self doSomething]; else [self doSomethingElse]; item1.isEqualToString:@"2" ? [self doSomething] : [self doSomethingElse]; //'?:' statement 
+6
source share
3 answers

Yes, there is a difference.

Semantically, the if / else statement means

 if (condition) statements else statements 

while ternary condition

 condition ? expression : expression 

so that you can assign the result of the?: operator until you can do it with the if statement. In fact, the operator ?: This is the expression itself, so you can nest it in other expressions, even others ?: Operator.

.?: type is also checked, this

 condition ? [self methodThatReturnsVoid] : [self methodThatReturnsInt] 

causes an error, because the type of result may change in accordance with the condition.

+16
source

There is a difference, as Jack suggests. You can rewrite the ?: Operator as follows:

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

In terms of efficiency, several sets of machine instructions have versions ?: Implemented in hardware for simple cases, but not for more complex cases (where they will use something similar to the above), so it's hard to say which is more effective when.

The main advantage of the ?: Operator is that it allows you to embed a conditional operation in a vs expression to break the expression with if / else, and this can make conceptually (and visually) simpler code, even though the actual complexity of the machine is not significant (if at all) reduced.

+6
source

To add the good answers provided by Jack and Hot Fix, determining what to use is partly dependent on need and partly on style. For example,?: As a rule, it reduces redundancy, which can lead to simpler and shorter codes that are easier to read and simplify for maintenance - there is no risk of updating one half of if..else and forgetting the other. eg.

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

against

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

This is a short example for brevity, but you can imagine that with real argument names and complex complexity it would be easy to return after a few months from now and change the second call of SomeFunction, without understanding the other, there is, not to mention the need, you can also change .

+1
source

All Articles