问题
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 V64
s 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