Actually you invoke undefined behavior with:
long double f = 1000000000 * 99999;
First, evaluate 1000000000 * 99999
, which is a multiplication of two int
objects. Multiplying two int
objects is always an int
. Since int
is not big enough to represent the result (most likely 32 bits), the upper bits are lost.
Since overflows in signed integer types is undefined, you just triggered undefined behavior. But in this case it is possible to explain what happened, even though it is UB.
The computation keeps only the lowest 32 bits, which should be (1000000000 * 99999) modulo (2**32) == 3571414528
. But this value is too big for int
. Since on PC int negatives are represented by two's complement, we have to subtract 2**32, every time 2**31<= result < 2**32
. This gives -723552768
Now, the last step is:
long double f = -723552768
And that is what you see.
To overcome the issue, either use long long
like this:
long double f = 1000000000LL * 99999;
Or double
:
long double f = 1000000000.0 * 99999;