Re: Can't find last element in list
On Apr 26, 9:05 pm, d...@furrfu.com (Drew Lawson) wrote:
In article <f0qs3n$et...@news.datemas.de>
"Victor Bazarov" <v.Abaza...@comAcast.net> writes:
Lawson wrote:
[..]
Common and hazardous pattern for that, assuming that you *have* to
return a pointer, is to return a null pointer for "not found." Just
make sure that any caller is testing for null.
And here is the kicker -- there is no way to "make sure that any
caller is testing". It's the caller's responsibility. All you can
do is document the proper way of using your function. This is
especially important for library designers. It's easy when you
design/implement both the function and the code that calls it.
What if you don't?
The C answer is culture -- learning that anything that returns a
pointer can return NULL. Here be dragons.
The professional answer doesn't depend on the language: you read
the documentation of a function before using it.
The C++ answer seems to be, "why do you need a pointer?"
For the OP's task, I'd lean more toward returning an index, but
that has the same out-of-bounds issues for the failure value. But
a subscripting exception is easier to debug than rogue-pointer
memory corruption. So this case has me sold on containers and
subscripts. (Still making the C --> C++ cultural shift.)
Actually, returning a null pointer is probably the most robust
and the easiest to debug. On most implementations,
dereferencing a null pointer will make the program go boom
immediately. Using an out of bounds index or a one-past-the-end
pointer will usually just return garbage; your program ends up
outputting wrong values, and you have to figure out why.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34