What does the question mark and the colon (?: ternary operator) mean in objective-c?

danielreiser picture danielreiser · Apr 7, 2010 · Viewed 339.3k times · Source

What does this line of code mean?

label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;

The ? and : confuse me.

Answer

Barry Wark picture Barry Wark · Apr 7, 2010

This is the C ternary operator (Objective-C is a superset of C):

label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;

is semantically equivalent to

if(inPseudoEditMode) {
 label.frame = kLabelIndentedRect;
} else {
 label.frame = kLabelRect;
}

The ternary with no first element (e.g. variable ?: anotherVariable) means the same as (valOrVar != 0) ? valOrVar : anotherValOrVar