views:

127

answers:

3
+2  Q: 

Data types in C

A long double is known to use 80 bits.

2^80 = 1208925819614629174706176;

Why, when declaring a variable such as:

    long double a = 1208925819614629174706175; // 2^80 - 1

I get a warning saying: Integer constant is too large for its type.

+13  A: 

1208925819614629174706175 is an integer literal, not a double. Your program would happily convert it, but it would have to be a valid integer first. Instead, use a long double literal: 1208925819614629174706175.0L.

Thom Smith
Ah, beat me to it +1
Marcin
It should be noted that there will be some loss of precision doing this. The mantissa of an 80-bit long double is generally 63 bits, so you get no better integer precision than with a long long.
Chris
long long long long?
Matt Joiner
@Chris, if that number is in fact 2^80, it fits exactly in ANY floating point type, even 32-bit float.
R..
2^80, yes. 2^80 - 1, no.
Chris
+2  A: 

The value 1208925819614629174706175 is first crated as a const int, and then converted to a long double, when the assignment happens.

Marcin
+5  A: 

Firstly, it is not known how many bits a long double type is using. It depends on the implementation.

Secondly, just because some floating-point type uses some specific number of bits it does not mean that this type can precisely represent an integer value using all these bits (if that's what you want). Floating-point types are called floating-point types because they represent non-integer values, which normally implies a non-trivial internal representation. Due to specifics of that representation, only a portion of these bits can be used for the actual digits of the number. This means that your 2^80 - 1 number will get truncated/rounded in one way or another. So, regardless of how you do it, don't be surprised if the compiler warns you about the data loss.

Thirdly, as other answers have already noted, the constant you are using in the text of your program is an integral constant. The limitations imposed on that constant have nothing to do with floating-point types at all. Use a floating-point constant instead of an integral one.

AndreyT