Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Language Basics

Operators and Expressions

Learn Objective-C arithmetic, comparison, logical, bitwise and assignment operators, precedence rules, and why == is wrong for comparing strings and objects.

Operators combine values into expressions. Because Objective-C is a superset of C, all the C operators work exactly as you know them. The new point is that objects are pointers, so the same symbols behave differently when applied to objects than to numbers. This lesson reviews every operator group, the precedence table you need, and the single most important rule for objects: == compares identity, not content.

Arithmetic operators

Operator Meaning Example Result
+ addition 5 + 2 7
- subtraction 5 - 2 3
* multiplication 5 * 2 10
/ division 5 / 2 2 (integers)
% remainder 5 % 2 1

% works only on integers. For floating-point remainders use the C function fmod from <math.h>. Dividing an integer by zero is undefined behavior; dividing a floating-point value by zero gives inf.

Increment and decrement come in prefix and postfix forms:

OBJECTIVEC
int i = 5;
int a = i++;   // a = 5, i = 6  (use, then add)
int b = ++i;   // i = 7, b = 7  (add, then use)

Assignment operators

= assigns. Compound forms combine an operation with assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=.

OBJECTIVEC
NSInteger total = 10;
total += 5;     // 15
total *= 2;     // 30

Assignment is itself an expression, which allows a = b = 0; but also lets a typo like if (x = 3) compile. The compiler warns about it with -Wall.

Comparison and logical operators

Comparison: ==, !=, <, >, <=, >=. Logical: && (and), || (or), ! (not). Results are int 0 or 1, and BOOL variables hold them as YES or NO.

&& and || use short-circuit evaluation: the right side runs only if needed. That makes this pattern safe:

OBJECTIVEC
if (name != nil && [name length] > 3) {
    NSLog(@"long name");
}

Comparing objects: the key rule

For a pointer, == asks "are these the same object in memory?" It does not ask "do they hold the same content?".

OBJECTIVEC
NSString *a = [NSString stringWithFormat:@"%d", 100];
NSString *b = [NSString stringWithFormat:@"%d", 100];

a == b;                   // NO: two different objects
[a isEqual:b];            // YES
[a isEqualToString:b];    // YES

Rules to remember:

  • Use isEqualToString: for strings, isEqualToNumber: for NSNumber, isEqualToArray: for arrays, and isEqual: for any object.
  • Use == with objects only to compare with nil or to ask if two names refer to the very same object.
  • Compare numbers with compare: when you need ordering: [a compare:b] returns NSOrderedAscending, NSOrderedSame or NSOrderedDescending.

Careful: string literals with identical text may be the same object, because the compiler merges them. That is an optimization you must never rely on.

Bitwise operators

& (and), | (or), ^ (xor), ~ (not), << and >> (shifts). They are the foundation of option sets, which Cocoa uses heavily:

OBJECTIVEC
typedef NS_OPTIONS(NSUInteger, ABCPermission) {
    ABCPermissionRead  = 1 << 0,
    ABCPermissionWrite = 1 << 1,
    ABCPermissionAdmin = 1 << 2,
};

ABCPermission p = ABCPermissionRead | ABCPermissionWrite;
if (p & ABCPermissionWrite) { /* can write */ }
p &= ~ABCPermissionWrite;     // remove the write flag

Enum details come in Constants, Enums and typedef.

The conditional (ternary) operator

condition ? valueIfTrue : valueIfFalse is an expression. GCC and clang also provide a short form that returns the left side when it is non-zero, which is handy with nil:

OBJECTIVEC
NSString *label = isAdmin ? @"Admin" : @"User";
NSString *display = nickname ?: @"Anonymous";   // nickname unless nil

Precedence and associativity

When operators are mixed, higher precedence is evaluated first. From highest to lowest, the groups you need are:

  1. (), [] (message and index), ., ->, postfix ++ --
  2. Unary: !, ~, -, * (dereference), &, sizeof, casts, prefix ++ --
  3. * / %
  4. + -
  5. << >>
  6. < <= > >=
  7. == !=
  8. &, then ^, then |
  9. &&, then ||
  10. ?:
  11. Assignments (right to left)

A frequent trap is if (x & 1 == 0): because == binds tighter than &, it means x & (1 == 0). Use parentheses when in doubt: if ((x & 1) == 0).

Stand-in: operator behaviour

This C program exercises the same arithmetic, comparison and bitwise rules.

C Stand-in (C): arithmetic, bits and precedence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: identity versus equality

C strings are pointers too, so they show the identity-versus-content distinction in the same way as NSString objects. == compares addresses; strcmp compares content, like isEqualToString:.

C Stand-in (C): == compares addresses, strcmp compares content

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Using == to compare NSStrings.
  • Forgetting that integer division truncates.
  • Writing = instead of == inside if.
  • Relying on operand evaluation order, such as a[i] = i++, which is undefined behavior.
  • Mixing bitwise & with logical &&; they are not interchangeable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which expression correctly checks whether two NSString objects hold the same text?

    isEqualToString: compares content. == compares pointers.
  2. 2. What is the value of -7 % 2 in C and Objective-C?

    The remainder takes the sign of the left operand in C99 and later, so -7 % 2 is -1.
  3. 3. What does the expression nickname ?: @"Anonymous" return when nickname is nil?

    The short ternary returns the left operand if it is non-zero, otherwise the right operand.
  4. 4. Why does if (x & 1 == 0) not test for an even number?

    It is parsed as x & (1 == 0). Parenthesize: (x & 1) == 0.

Summary

  • Objective-C inherits every C operator: arithmetic, comparison, logical, bitwise, assignment and ternary.
  • && and || short-circuit, which is the safe way to guard against nil or NULL.
  • Objects must be compared with isEqual: and friends; == only tests identity.
  • Bit flags combine with |, test with & and clear with & ~.
  • Use parentheses whenever precedence is not obvious.

Next: Constants, Enums and typedef