What is 1.#INF and why does casting to a float or double prevent a division by 0 of crashing?
Also, any great ideas of how to prevent division by 0? (Like any macro or template)?
int nQuota = 0;
int nZero = 3 / nQuota; //crash
cout << nZero << endl;
float fZero = 2 / nQuota; //crash
cout << fZero << endl;
if I use instead:
int nZero = 3 / (float)nQuota;
cout << nZero << endl;
//Output = -2147483648
float fZero = 2 / (float)nQuota;
cout << fZero << endl;
//Output = 1.#INF
1.#INFis positive infinity. You will get it when you divide a positive float by zero (if you divide the float zero itself by zero, then the result will be “not a number”).On the other hand, if you divide an integer by zero, the program will crash.
The reason
float fZero = 2 / nQuota;crashes is because both operands of the/operator are integers, so the division is performed on integers. It doesn’t matter that you then store the result in a float; C++ has no notion of target typing.Why positive infinity cast to an integer is the smallest integer, I have no idea.