gpt4 book ai didi

c - 为什么 C 不提供结构比较?

转载 作者:太空狗 更新时间:2023-10-29 16:35:06 25 4
gpt4 key购买 nike

正如大多数 C 程序员所知,您不能直接比较两个结构。

考虑:

void isequal(MY_STRUCT a, MY_STRUCT b)
{
if (a == b)
{
puts("equal");
}
else
{
puts("not equal");
}
}

a==b 比较将 AFAIK 在任何明智的 C 编译器上抛出编译错误,因为 C 标准不允许内置结构比较。由于对齐、打包、位域等原因,使用 memcmp 的解决方法当然不是一个好主意,因此我们最终编写了一个元素一个元素的比较函数。

另一方面,它确实允许结构分配,例如a = b 是完全合法的。很明显,编译器可以轻松应对,那么为什么不进行比较呢?

我唯一的想法是结构赋值可能与 memcpy() 相当接近,因为对齐等造成的间隙无关紧要。另一方面,比较可能更复杂。或者这是我缺少的东西?

很明显,我知道做一个简单的逐个元素的比较是不够的,例如如果该结构包含一个指向字符串的指针,但在某些情况下它会很有用。

最佳答案

正如其他人所提到的,这里是 C: A Reference Manual 的摘录哈比森和斯蒂尔:

Structures and unions cannot be compared for equality, even though assignment for these types is allowed. The gaps in structures and unions caused by alignment restrictions could contain arbitrary values, and compensating for this would impose an unacceptable overhead on the equality comparison or on all operations that modified structure and union types.

关于c - 为什么 C 不提供结构比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7179174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com