fuzzygoat
fuzzygoat

Reputation: 26223

Do "!" and "nil" give the same result?

In objective-c is the end result of !variable the same as variable==nil Also I think I read somewhere that iVars are initialized to "nil" (i.e. o) but sadly I can't seem to find where I spotted it now. If I am correct is this initialization to nil part of declaring an iVar or is it linked to something else like @property?

i.e. do these evaluate the same ...

if(!myObject) ...

and

if(myObject == nil) ...

Cheers Gary.

Edited: hopefully for more clarity.

Upvotes: 3

Views: 125

Answers (3)

slycrel
slycrel

Reputation: 4285

In objective-c the ! is a boolean operator and returns the opposite of a boolean value or expression result. In the below example myObj is really evaluating it's pointer value as a boolean, zero or non-zero. Since myObj is a non-zero pointer this evaluates to true. !myObj will return the opposite, in this case it would return false.

id myObj = nil;
int x = 0;
if (myObj)
  x++;

Upvotes: 1

Chuck
Chuck

Reputation: 237010

Your question subject and question body appear to be asking different things, so…

To answer the question subject: No, ! and nil are not at all the same. ! is an operator that returns the logical negation of its operand (that is, !0 returns 1 and ! with anything else returns 0), while nil is a macro for 0.

To answer the question itself: Yes, !foo and foo == nil give the same result for object variables. And yes, instance variables are initialized to 0. So are static variables and global variables.

Upvotes: 3

mouviciel
mouviciel

Reputation: 67829

! is a C logical operator that means not (like && means and and || means or).

nil is the way for expressing an unitialized object pointer.

Applied to a pointer, the value of the expression is TRUE whenever the pointer is NULL or nil.

In the end, if(!myObject) and if(myObject==nil) have the same behaviour.

Upvotes: 1

Related Questions