stumped
stumped

Reputation: 3293

Objective-C operator (?) and (:)

What do the ? and : signify here?

#define MAX(a,b) ( ((a) > (b)) ? (a) : (b) )

Upvotes: 4

Views: 7415

Answers (4)

Kjuly
Kjuly

Reputation: 35131

?: is a ternary operator. What ((a) > (b)) ? (a) : (b) stands for is:

if (a > b)
  return a
else
  return b

Refter it HERE.

Upvotes: 8

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

This is a ternary operator (also available in C, to which Objective C is a superset, and other languages that borrowed from it).

The expression before ? is evaluated first; if it evaluates to non-zero, the subexpression before : is taken as the overall result; otherwise, the subexpression after the colon : is taken.

Note that subexpressions on both sides of : need to have the same type.

Also note that using macro for calculating MAX may produce unexpected results if arguments have side effects. For example, MAX(++a, --b) will produce a doubled side effect on one of the operands.

Upvotes: 13

TeaCupApp
TeaCupApp

Reputation: 11452

As Kjuly mentioned it should be greater than sign, It's just an if statement.

(a > b) ? a : b

If a is greater than b then a will be returned from MAX(a,b) function or if b is greater then if statement will be false and b will be returned.

The ternary (conditional) operator in C

Check Evan's answer

Upvotes: 9

Brandon
Brandon

Reputation: 3494

This is a sort-of shorthand notation for a conditional. a ? b : c.

If a evaluates to true, then b, else c.

I believe this should be: #define MAX(a,b) ( ((a) > (b)) ? (a) : (b) )

so basically, if a is greater then b, then a, else b

Upvotes: 4

Related Questions