Single-function comparison of Union values

╄→гoц情女王★ 提交于 2019-12-25 05:38:31

问题


I have a union defined as follows:

union V64
{
    double f64;
    __int64 i64;
    unsigned __int64 u64;
};

I'd like to do a lazy comparison (equality and inequality) of a 8-byte value of unknown type against another V64 of known type. Will comparing the i64 of two V64s consistently give me the expected result, regardless of the underlying type? For example:

V64 a.u64 << 9007199254740993+500;  //pseudo-code reading raw bytes
V64 b.u64 << -9007199254740993-501; //pseudo-code reading raw bytes
if(a.i64 > b.i64)
{/*do stuff*/}

Comparing u64 breaks down when one is negative and f64 breaks down when the value exceeds double's int storage (2^53 +1). Comparing i64 appears to work, but there might be a case I haven't considered.


回答1:


After you assign to two members of the same type, you can compare them:

a.f64 = 5.0;
b.f64 = -1.0;

if (a.f64 < b.f64) { /* ... */ }

You can only read the union member that was last written to. So you could compare a.f64 and c.u64, but that would just promote both values to double.



来源:https://stackoverflow.com/questions/16091682/single-function-comparison-of-union-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!