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

发布于 2024-08-14 11:11:18 字数 355 浏览 4 评论 0原文

尽管我是一名长期的 C 程序员,但我最近才知道可以直接将结构变量相互赋值,而不是使用 memcpy:

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

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

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

标准有什么充分的理由排除这一点吗?或者这与——原本非常优雅的——标准不一致?

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

Even though I am a long time C programmer, I only recently learned that one can directly assign structure variables to one another instead of using memcpy:

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

Though this feels a bit "high-level" for C, it is definitely useful. But why can't I do equality and inequality comparison:

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

Is there any good reason for the standard to exclude this? Or is this an inconsistency in the - otherwise very elegant - standard?

I don't see why I can replace my memcpy's for clean assignments, but I have to keep those ugly memcmp's in place.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风情万种。 2024-08-21 11:11:18

根据 comp.lang.c 常见问题解答

编译器没有什么好的办法
实施结构比较
(即支持 == 运算符
结构),这与
C的低级风味。一个简单的
逐字节比较可能会失败
未使用中存在的随机位
结构中的“洞”(例如
padding 用于保持对齐
后面的字段正确)。逐个字段的比较可能需要不可接受的数量
大型结构的重复代码。
任何编译器生成的比较
无法预期进行比较
指针字段在所有
情况:例如,经常
适合比较 char * 字段
使用 strcmp 而不是 ==。

如果您需要比较两个结构,
你必须编写自己的函数
逐个字段地执行此操作。

Per the 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文