why float-pointing numbers don't overflow to infinity

Viewed 93

Let's say we have the following code:

float f = 999999999999*9999999999999999*999999999999; //a large number to make it overflow

so according to the float-pointing rule, the result should be infinity as: enter image description here

But I checked the result's bit representation , it is not the infinity, it is some else, how come?

1 Answers

None of the values in 999999999999*9999999999999999*999999999999 are floating points, so you aren't doing floating point arithmetic. In fact, even without any extra warning options set, gcc gives me this warning for your code (clang gives a similar warning):

warning: integer overflow in expression of type 'long int' results in '4467987020393345025' [-Woverflow]

Do this instead

float f = 999999999999.0f*9999999999999999*999999999999;
printf("%f\n", f);

output:

inf

Making the first literal a floating point number forces floating point arithmetic, so you get the infinite value you want.

Related