我正在阅读有关搜索和排序功能的 GLibC 引用
here和 here在其中一个代码示例中,使用了类型转换,而在另一个代码示例中,它不是:
第一:
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);
}
第二个: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);
}
在第二个示例中,是否有任何原因,例如const struct critter *c1 = (const struct critter *)v1;
没用过?或者这只是为了简洁?编辑:如果编译器可以推断出它,那么在第一个示例中是否需要强制转换?这种事情有什么最佳实践吗?
最佳答案
与 void *
之间的转换并且任何对象指针类型都可以在没有强制转换的情况下安全地完成。这在 C standard 的第 6.3.2.3p1 节中指定:
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.
因此,第二个函数就可以了,第一个函数可以安全地写为:
int
compare_doubles (const void *a, const void *b)
{
const double *da = a;
const double *db = b;
return (*da > *db) - (*da < *db);
}
作为一般规则,除非绝对必要,否则不应强制转换。
关于何时以及何时不在 C 中进行类型转换存在冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68545468/