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.