"Why Tea" <yt****@gmail.c omwrote in message
news:a9******** *************** ***********@p69 g2000hsa.google groups.com...
>I understood that the CPU registers determine the size of the machine.
But what is the correct way to code an arithmetic operation to avoid
wrap-around when the code is to be run on both 32-bit and 64-bit
machines?
it depends on who you ask...
it is perfectly possible to have a 32 bit machine with some 64 or 128 bit
registers (as is the case with MMX and SSE).
the issue is not quite as clear-cut as it may seem.
Example:
uint32_t x = SOME_LARGE_NO;
uint64_t y;
...
y = (uint64_t)(1000 0 * x); /* Will overflow occur before the cast? */
y = (int64_t)(x) * 10000; /* or, is it better to do the cast first?
*/
Please comment.
my answer:
y = ((int64_t)x) * 10000;
reason:
casts change the output type, not the input type.
so, yeah, in the first case, the overflow may well occur before cast to the
larger type. however, afaik, what happens, exactly, is up to the compiler
(for example, it may internally upcast when loading, for example because the
arch may have a load-and-extend instruction, wheras to load and then up-cast
would involve additional instructions).
and so on...
/Why Tea