2

Possible Duplicate:
ObjectiveC: if (obj) {…} AND if (obj != nil) {…}, which is better?

Is there a difference between these two conditions:

if (!object) {
 // do something
}

and . . .

if (object == nil) {
 // do something
}
Community
  • 1
  • 1
Sean Danzeiser
  • 9,141
  • 12
  • 52
  • 90

2 Answers2

9

No, there is no difference. Both of those examples are exactly the same. From the C spec 6.5.3.3 Unary arithmetic operators:

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

Since nil is 0, that last sentence applies exactly.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • 2
    On iOS, nil is defined as ((void *)0) - so this may be invalid if `object` wasn't a pointer. –  Aug 12 '12 at 21:41
  • 2
    @H2CO3, yes, I was assuming `object` is a pointer. If it's not, comparing against `nil` is wrong anyway. – Carl Norum Aug 12 '12 at 21:43
  • 2
    of course, that's a valid assumption. :) Just a minor point. –  Aug 12 '12 at 21:45
1

If object is of type id or any valid Objective-C object, then only one difference is present: readability. (i. e. from the compiler's point of view, they're both the same.)

However, there may be examples when comparing to nil wouldn't be very nice. For example, if for some evil illogocal reason, object was an int, only the two following statements would be valid:

if (object == 0)

and

if (!object)

and they would again be equivalent, but comparing an int to a pointer (which nil is) - except if the integer is an explicit constant 0 - is illegal and most likely result in a compiler warning (in most cases, it would still work, however...)