Jack Hopson said:
I see a lot of code that explicitily typecasts void* to
a specific pointer type eg a pointer returned by malloc.
I think it's safe to say that the majority of C programmers
who do this are aping other C programmers (even authors of
C books) who have also merely seen it, but never really
understood why they do it, let alone why they should or
shouldn't.
That isn't to say there aren't C programmers who know what
they're doing when they cast malloc. Some use C++ compilers
on C code precisely because of it's stricter requirements,
such as requiring function prototypes.
There is also lots of code that relies on implicit
typecasting of void*.
Which is preferable?
The whole point of the implicit conversion of void * in C
is to write generic code easily. Unfortunately, it's not a
fashion that has taken off in C. Despite the cleaner syntax,
it is still difficult to do, and most bugs and problems
centre around the type weakness that was meant to make
things simpler.
It is generally preferable to avoid casts. You generally
only use casts in C when it is obvious that they are correct.
Consider...
printf("%02X", 'A' + 0u);
printf("%02X", (unsigned) 'A');
Here %X requires an unsigned int. The cast ensures that, but
as the first statement shows, it's not strictly necessary.
This is an example of where most C programmers would actually
prefer to see the cast, because the implicit conversion in
the earlier argument is not immediately apparent at a glance.
Of course, it can be also done as...
unsigned x = 'A';
printf("%02X", x);
But that comes at the cost of declaring a variable. Apart
from the aesthetics, every line of code is an opportunity
for something (else) to go wrong.
Everything is a trade-off. Casts are no exception.