Re: nil pointers
Re: nil pointers
- Subject: Re: nil pointers
- From: Uli Kusterer <email@hidden>
- Date: Tue, 11 Jul 2006 18:20:06 +0200
Am 11.07.2006 um 04:59 schrieb Adam Johnson:
why do Cocoa developers declare pointers as nil, then define them?
Well, not everyone does it. However, many C (and by extension
Cocoa) programmers do this because it makes it easier to catch when
you're accessing an uninitialised variable.
This was especially handy in ye olde (pre- C99) days, when you had
to declare variables at the start of a block. In pseudocode:
window theWindow = [new window]
[theWindow mapToScreen]
button theBtn = [new buttonIn: theWindow]
If you have to declare all variables at the top, you have to rewrite
this as:
window theWindow = [new window]
button theBtn
[theWindow mapToScreen]
theBtn = [new buttonIn: theWindow]
Now, when someone later inserts another call after mapToScreen and
accidentally makes use of theBtn, he'll access an invalid pointer (in
this case that'd be obvious, but if this was a more complex function,
it might be harder to spot). So, what people do is set theBtn to NULL
(or NIL, or whatever) so you either (in plain C) get an access fault
right away, or (in Cocoa) wonder why your message doesn't stick and
see the variable is still NIL.
It's not that important anymore with newer C compilers, but often
people mess around with code trying to work out how to best implement
something and just *want* the declaration on a separate line from the
implementation for better text editing (e.g. you try three different
versions of initialising the variable, but the declaration stays the
same). Similarly, when there is a very long class name, it's often
easier to read that when it's split on two lines that way.
So, it's usually not strictly necessary in the case where an
initialisation could happen on the same line, but often it's a sign
of healthy paranoia that pays off in having to do less debugging
because the code is more readable or errors are easier to spot.
Cheers,
-- M. Uli Kusterer
http://www.zathras.de
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
References: | |
| >nil pointers (From: "Adam Johnson" <email@hidden>) |