I am currently studying objective-c and the basic c programming language.
I have a questions about a particular line of code:
if (!balance)
Balance is an object that is created. I understand that this code is checking to see if the object balance is nil or not, is this correct?
Could somebody please explain how exactly the code checks for nil? Does it return 0 if the value of balance is nonzero and 1 if the value is 0?
Thanks in advance.
First you need to understand how
if
works. Basically, any non-zero value is treated as true and a zero value is treated as false.Something as simple as
if (10)
will be treated as true whileif (0)
is treated as false.Any expression evaluates to either a value of zero or a non-zero value.
An object pointer is just a number - a memory address. A
nil
pointer is simply an address of 0. Any non-nil pointer will have a non-zero address.The
!
operator negates that state. A non-zero value will be treated as a zero value and visa-versa.So now combine all of this.
In Objective-C,
nil
is roughly analogous to0
,NULL
orfalse
, but for object pointers. In anif
statement, it will behave the same as one of the aforementioned scalar values. For example, the following twoif
statements should produce the same results:NSLog should return (null) (which probably is description for nil), not NULL in console. Your check should look like this:
If
balance
isnil
then it will be a pointer to0x0
. That address is never used for a valid object.In C anything within an
if
that evaluates to zero is considered a negative response, anything that evaluates to non-zero is a positive response.Pointers evaluate to their address — exactly as if you cast them to an integral type. The
!
means "NOT".So the test is
if(address of balance is not zero)
.