Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What does this line of code mean?

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

The ? and : confuse me.

like image 758
danielreiser Avatar asked Apr 07 '10 19:04

danielreiser


People also ask

What is the question mark in ternary operator?

“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value.

What does the question mark mean in C?

The question mark operator, ?:, is also found in C++. Some people call it the ternary operator because it is the only operator in C++ (and Java) that takes three operands. If you are not familiar with it, it's works like an if-else, but combines operators.

What symbols we use in ternary operator in C?

The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.

What are the three arguments of a ternary operator?

The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.


2 Answers

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

like image 57
Barry Wark Avatar answered Sep 30 '22 22:09

Barry Wark


It's the ternary or conditional operator. It's basic form is:

condition ? valueIfTrue : valueIfFalse 

Where the values will only be evaluated if they are chosen.

like image 34
Sean Avatar answered Sep 30 '22 23:09

Sean