c - 为什么我可以分配结构但不能比较它们

标签 c struct compare assign

尽管我是一名资深的 C 程序员,但我最近才了解到可以直接将结构变量分配给彼此而不是使用 memcpy:

struct MyStruct a,b;
...
a = b; /* implicit memcpy */

虽然这对 C 来说感觉有点“高级”,但绝对有用。但是为什么我不能做平等和不平等的比较:

if (a == b) ...
if (a != b) ...

标准是否有充分的理由将其排除在外?或者这是否与 - 否则非常优雅 - 标准不一致?

我不明白为什么我可以替换我的 memcpy 来进行干净的分配,但我必须保留那些丑陋的 memcmp。

最佳答案

根据 comp.lang.c FAQ :

There is no good way for a compiler to implement structure comparison (i.e. to support the == operator for structures) which is consistent with C's low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. Any compiler-generated comparison could not be expected to compare pointer fields appropriately in all cases: for example, it's often appropriate to compare char * fields with strcmp rather than ==.

If you need to compare two structures, you'll have to write your own function to do so, field by field.

关于c - 为什么我可以分配结构但不能比较它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1882974/

相关文章:

c - C 中带索引的指针和数组

vb.net - 用于将一个 PDF 与另一个 PDF 进行比较的 .Net 工具或库

java - 找出数组类型来比较java中的数组

c - C 中的地址 : &(number)

c - 如何将此结构放入动态分配的空间中?

c - C中带指针的嵌套结构

在两个结构体数组变量之间复制数据

c - 指向结构的指针数组中的指针,如果设置为 NULL,是否分配内存?

c# - .net 中类和结构之间的实际区别(不是概念上的)?

java - 有没有办法比较列表中的两个对象并组合它们的最佳值?(Java)