gpt4 book ai didi

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

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

尽管我是一名资深的 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/

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