I have been given a legacy code, where someone(s) have carelessly assigned double
values to int
variables like:
int a = 10;
double b = 20;
a = b;
Now to get rid of the
warning C4244: '=': conversion from 'double' to 'int', possible loss of data
warnings, I tried editing the code upstream and get rid of the unnecessary double
variables, but it turns out to be too messy!
I could also use casting:
a = (int) b;
but actually there is no guarantee that b
will be within the limits of an integer. I thought of making a helper function:
int safeD2I(double inputVar){
if ((inputVar < INT_MAX) && (INT_MIN < inputVar)){
return (int) inputVar;
} else {
exit(-1);
}
}
but I'm not sure if this is the best implementation. I was wondering if there is a more canonical way to handle this issue?
what I want:
- in the case the
b
variable being outside of the integer bounds, the program stops immediately - prints an error message to the terminal indicating that the specific line and time when this issue happened.
Thanks for your support in advance.
if ((inputVar < INT_MAX) && (INT_MIN < inputVar)){
fails edge cases.Wrong edges as it is more like, but not exactly like
(inputVar < INT_MAX + 1) && (INT_MIN - 1 < inputVar)
Be wary of code like
some_FP < SOME_INT_MAX
asSOME_INT_MAX
may not convert to the FP value needed due to the integer type may have more precision that the FP one. This is not usually a problem withint, double
.Test if the
double
is within the range of(INT_MIN-1 .... INT_MAX+1)
1. Note () and not [].If not, error out or handle in some defined way of your choosing.
Assuming typical 2's complement, but not assuming the precision of
double
exceedsint
(more useful to migrate code tofloat, long long
that way), some sample code:To record the line where this failed, consider a macro to pass the line number.
1 Example -2,147,483,648.9999... to 2,147,483,647.9999...