Calculating the range of long in C using formula

Viewed 99

I'm working on Exercise 2-1 in K&R, and part of that exercise is determining the range of the long data type by printing out the values from limits.h and calculating them.

When I print out the values from limits.h, I get the minimum value for long being -9223372036854775808 and the maximum value for long being 9223372036854775807.

I wasn't exactly sure how to calculate the range, but using the formula from this post seems to work for char, int, and short: data type range forumlas.

When I use the above formulas, I get the minimum value for long being -9223372036854775808 and the maximum value for long being 9223372036854775808.

You're probably thinking that I just forgot to subtract 1 from the maximum value, but in fact I do subtract one. These are my statements for printing and calculating the min and max values for long:

printf("min val of long: %.0f\n", pow(2, sizeof(long) * 8) / -2);
printf("max val of long: %.0f\n\n", (pow(2, sizeof(long) * 8) / 2) - 1);

Does anyone understand why there is a discrepancy between the max value which I printed out from limits.h and the max value which I calculated?

1 Answers

The reason you don't see the value you expect is because the sequence of representable values in a typical double (returned by pow()) is:

...
9223372036854774784
9223372036854775808
9223372036854777856
...

That is, a double (IEEE 754) does not have enough bits of mantissa to represent the integer you are expecting. 9223372036854775808 is one of the integers that can be represented exactly because it is a power of 2.

If you want to get the maximum value, you can carefully convert your formula to the integer domain and the << operator:

const long x = (1UL << (sizeof(long) * 8 - 1)) - 1;
printf("%li\n", x);
Related