I am a bit confused of the point of having this warning:
Arithmetic overflow: Using operator '' on a 4byte value and then casting the result to a 8byte value. Cast the value to the wider type before calling '' operator to avoid overflow.
#include <iostream>
using std::cin;
using std::cout;
using std::ios_base;
int main() {
cout.setf(ios_base::fixed, ios_base::floatfield);
double mints = 10.0 / 3.0;
const float c_MILLION = 1e6;
cout << "\n10 million mints: " << 10 * c_MILLION * mints;
cin.get();
}
According to my understanding when we multiply a float value with a double value we are basicaly multiplying a 4byte value to an 8byte value and it we will hence, lose some precision according to the links that I have read:
However, when I do output this, I get a double value
https://i.sstatic.net/EOQzm.png
If that is the case, why does it bother to warn me to cast c_MILLION to double value if it is automatically changing it to a double result? It cant convert an 8byte value to a 4byte value anyways. So, why does it bother to warn the programmers when it is already saving us from this trouble?
Or can it convert an 8byte value to a 4byte value as well. If so, how does it determine what type to print? This is a question that I cannot find the answer to from the links I read.
If it automatically converting the result to 8byte value, what is the point of displaying this warning?
Here is the warning:
https://i.sstatic.net/L2szy.png
Severity Code Description Project File Line Suppression State
Warning C26451 Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to avoid overflow (io.2)
The problem was that I was multiplying an int
value with a double
value. But still the warning should not exist when it automatically converts the multiplication of an int
to double
to a double
value.
The warning is because of this multiplication: 10 * c_MILLION
. There can be some values of c_MILLION
where some precision is lost that would not have been lost if c_MILLION
was first converted to a double
. Since the result of this multiplication is converted to double
, a mistaken programmer might assume that no precision was lost beyond what might be expected if the operands were double
in the first place. Hence the warning.