结构上溢出的整数加法 [英] Integer addition with overflow on a struct
问题描述
有 ULARGE_INTEGERunion 用于不支持 64 位算法的编译器.
There is the ULARGE_INTEGER union for compilers that don't support 64 bit arithmetic.
如果最后一行的加法溢出,下面的代码会发生什么?
What would happen in the following code if the addition on the last line overflows?
ULARGE_INTEGER u;
u.LowPart = ft->dwLowDateTime;
u.HighPart = ft->dwHighDateTime;
u.LowPart += 10000; //what if overflow?
推荐答案
ULARGE_INTEGER
由两个无符号值组成.无符号值保证可以环绕,因此在某种意义上它们不能溢出".
ULARGE_INTEGER
is composed of two unsigned values. Unsigned values are guaranteed to wrap round, so in some sense they can't "overflow".
如果回绕确实发生,u.LowPart
最终将小于 10,000.你可能想要的是:
If wrap round does occur, u.LowPart
will end up being less than 10,000. What you probably want is:
u.LowPart += 10000;
if (u.LowPart < 10000) u.HighPart++;
...但是现在哪个编译器仍然不支持 64 位整数?自 2011 年以来,C++ 标准和 C 标准自 1999 年以来一直要求使用它们.所以您真正想要的是:
... but what compiler still doesn't support 64-bit integers these days? They have been required by the C++ standard since 2011, and the C standard since 1999. So what you really want is:
u.QuadPart += 10000; // Forget about legacy compilers that doen't support 64 bits.
这篇关于结构上溢出的整数加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!