使用联合来代替明确定义的施法? [英] Is using an union in place of a cast well defined?

查看:142
本文介绍了使用联合来代替明确定义的施法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天早上和一位同事讨论了关于检测字节序的编码技巧的正确性。

I had a discussion this morning with a colleague regarding the correctness of a "coding trick" to detect endianness.

诀窍是:

bool is_big_endian()
{
  union
  {
    int i;
    char c[sizeof(int)];
  } foo;


  foo.i = 1;
  return (foo.c[0] == 1);
}

对我来说, union 不正确,因为设置联合的一个成员并读取另一个成员是定义良好。但我必须承认,这只是一种感觉,我缺乏实际的证据来加强我的观点。

To me, it seems that this usage of an union is incorrect because setting one member of the union and reading another is not well-defined. But I have to admit that this is just a feeling and I lack actual proofs to strengthen my point.

这招是正确的吗?谁在这里?

Is this trick correct ? Who is right here ?

推荐答案

您的代码不可移植。它可能在一些编译器上工作,也可能不工作。

Your code is not portable. It might work on some compilers or it might not.

当你尝试访问联合的非活动成员时,你的行为是未定义的是正确的]

You are right about the behaviour being undefined when you try to access the inactive member of the union [as it is in the case of the code given]

$ 9.5 / 1

$9.5/1


最多有一个数据成员可以随时处于活动状态,也就是说,数据成员中至多有一个可以随时存储在联合中。

In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data members can be stored in a union at any time.

因此 foo.c [0] == 1 不正确,因为 c 当前处于非活动状态。如果您认为我错了,请随时纠正我们。

So foo.c[0] == 1 is incorrect because c is not active at that moment. Feel free to correct me if you think I am wrong.

这篇关于使用联合来代替明确定义的施法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆