8

Working on my way to solve exercise 2.1 from "The C programming language" where one should calculate on the local machine the range of different types like char, short, int etc. but also float and double. By everything except float and double i watch for the overflow to happen and so can calculate the max/min values. However, by floats this is still not working.

So, the question is why this code prints the same value twice? I thought the second line should print inf

float f = 1.0;
printf("%f\n",FLT_MAX);
printf("%f\n",FLT_MAX + f);
Vladimir
  • 1,045
  • 1
  • 11
  • 23

2 Answers2

5

Try multiplying with 10, and if will overflow. The reason it doesn't overflow is the same reason why adding a small float to an already very large float doesn't actually change the value at all - it's a floating point format, meaning the number of digits of precision is limited.

Or, adding at least that last significant digit would likely work:

float f = 3.402823e38f; // FLT_MAX
f = f +   0.000001e38f; // this should result in overflow
vgru
  • 49,838
  • 16
  • 120
  • 201
2

The reason why it prints the same value twice is that 1.0 is too small to be added to FLOAT_MAX. A float has usually 24 bits for the mantissa, and 8 bits for the exponent. If you have a very large value with an exponent of 127, you would need a mantissa with at least 127 bits to be able to add 1.0.

As an example, the same problem exists with decimal (and any other) exponential values: If you have a number with 3 significant digits like 1.00*106, you can't add 1 to it because this would be 1'000'001, and this requires 6 significant digits.

You could overflow a float by doubling the value repeatedly.

alain
  • 11,939
  • 2
  • 31
  • 51