Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer addition with overflow on a struct [duplicate]

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?

Related question: What is the point of the ULARGE_INTEGER union?

like image 437
Roland Avatar asked Dec 10 '25 17:12

Roland


1 Answers

ULARGE_INTEGER is composed of two unsigned values. Unsigned values are guaranteed to wrap round, so in some sense they can't "overflow".

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++;

... 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.
like image 157
Martin Bonner supports Monica Avatar answered Dec 13 '25 06:12

Martin Bonner supports Monica