I was reading the GLibC reference on the searching and sorting functions here and here and in one of the code examples, typecasting is used while in the other, it is not:
First one:
int
compare_doubles (const void *a, const void *b)
{
const double *da = (const double *) a;
const double *db = (const double *) b;
return (*da > *db) - (*da < *db);
}
Second one:
int
critter_cmp (const void *v1, const void *v2)
{
const struct critter *c1 = v1;
const struct critter *c2 = v2;
return strcmp (c1->name, c2->name);
}
Is there any reason why in the second example, something like
const struct critter *c1 = (const struct critter *)v1;
was not used? or was this done only for brevity?
Edit: Is casting in the first example necessary then if the compiler can deduce it? Are there any best practices for this kind of thing?
A conversion to or from void *
and any object pointer type can safely be done without a cast. This is specified in section 6.3.2.3p1 of the C standard:
A pointer to
void
may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer tovoid
and back again; the result shall compare equal to the original pointer.
Because of this, the second function is fine as is and the first function can safely be written as:
int
compare_doubles (const void *a, const void *b)
{
const double *da = a;
const double *db = b;
return (*da > *db) - (*da < *db);
}
As a general rule, you shouldn't cast unless you absolutely have to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With