Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conflicted on when and when not to typecast in C?

Tags:

c

casting

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?

like image 251
First User Avatar asked Jul 27 '21 13:07

First User


Video Answer


1 Answers

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 to void 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.

like image 167
dbush Avatar answered Sep 27 '22 18:09

dbush