So many people I have noticed in their code use casts. Something
Richard Heathfield said once very much sticks out in my mind. If code is
written properly there is no need (or rarely) for casts. Why do they seem to
be used so much then?
That's the same question as asking why people use "void*". Its used
whenever you are doing any sort of polymorphic behavior. Often is
makes sense to create a generic function like:
int parseLines (void * ctx, int (* cb) (void *ctx, const char *
line), const char * input);
The idea is that you parse your input into a sequence of lines. But
you don't predetermine what it is you are going to do with each of
those lines. You can, in fact, reuse this code for any time you want
to send a sequence of lines to some processing. So the idea is that
for each line, the function:
cb (ctx, line);
is called with, say, negative results used as an abort code that is
passed out of parseLines(). Note that ctx is just being passed
through down from the callers straight through to the cb function.
Now, if you only ever use one callback function (cb) then you might as
well hard code it and pick the exact type for ctx (which keeps track
of whatever state you require, like say an MD5 accumulator, or
whatever) and not both with this level of abstraction. But the point
is that if you want to use various different callbacks which have
various different states, then forcing the state to be held in a void
* pointer lets you write parseLines() only once.
Your cb function itself would take the (void*) ctx pointer and cast it
back to the pointer to the state structure that it knows how to
handle.
As you can see, unless you can rewrite parseLines() with macros
(highly undesirable) the way you can achieve re-usability or
genericity is through the use of void *, which will ultimately require
a cast to re-establish your type. Trying to absolutely avoid casts at
all costs is really not worth it. You should probably minimize the
use of them, but sometimes it is truly best to use them.