2

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
  • 1
    Always prefer double when using floating-point values.
    – pmg
    Jul 2, 2020 at 12:15

1 Answer 1

8

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.