There are three variables with the following types
uint64_t old_addr, new_addr;
int delta;
and I want to do this assignment
new_addr = old_addr + delta;
However the problem is, when old_addr=915256 and delta=-6472064, the new_addr becoms 18446744069414584325
to fix that I have to check some things:
if ( delta < 0 ) {
if ( old_addr < abs(delta) )
new_addr = 0;
else
new_addr = old_addr + delta;
}
Is there a better and efficient way?
The question is what values
old_addrandnew_addrcan take. And whythey are
uint64_t, rather than simplyint. The simplest expressionwould be:
, but if
old_addrcan be greater thanINT_MAX, this won’t work.Otherwise, the rules of mixed signed/unsigned arithmetic in C/C++ are
such that you’re probably safest using explicit
ifs, and not riskingany mixed arithmetic before being sure of the values.
And note that on most machines,
abs( delta )will still be negative ifdeltais equal toINT_MIN. To correctly handle all of the cases,you’ld need something like:
(Just off the top of my head. There could easily be an off by one error
in there.)