何时以及何时不在 C 中进行类型转换存在冲突?

标签 c casting

我正在阅读有关搜索和排序功能的 GLibC 引用
herehere在其中一个代码示例中,使用了类型转换,而在另一个代码示例中,它不是:
第一:

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

相关文章:

c - 奇怪的代码崩溃问题?

c - 将 wchar_t 定义为 2byte

C、动态分配一个矩阵: Why is this not allowed?

GWT 的 java.lang.IllegalCastException

objective-c - 是否可以将 NSDictionary 转换为具有匹配属性的对象?

c - 模块函数不返回答案

c - 如何将字符串中的字符交换为枚举字符串?

C++ 指针转换

c++ - 为什么虚函数会破坏我的转换?

python - Numpy float 促销不一致