Why does casting a large double to a long sometimes return a positive and other times return a negative value in C?

StackOverflow https://stackoverflow.com/questions/23254839

Question

I put this into an iOS test case and ran it in the (32 bit iPad) simulator:

double whu = 3166323616091.220215;
NSLog(@"Double: %f", whu);
NSLog(@"Long:   %ld", (long)whu);
NSLog(@"Double: %f", 3166323616091.220215);
NSLog(@"Long:   %ld", (long)3166323616091.220215);

The output is:

2014-04-23 13:40:50.904 xctest[53336:303] Double: 3166323616091.220215
2014-04-23 13:40:50.905 xctest[53336:303] Long:   -2147483648
2014-04-23 13:40:50.906 xctest[53336:303] Double: 3166323616091.220215
2014-04-23 13:40:50.907 xctest[53336:303] Long:   2147483647

I get why it truncates the big double value to the max value for long (32bit). But why does casting the variable return the negative value when casting the literal returns a positive value? In fact, I don't understand why the negative is returned at all. Am I missing something having to do with precision, perhaps?

Was it helpful?

Solution

Casting a variable will result in the runtime code doing the conversion and the resulting overflow is producing the max negative number (0x80000000 an undefined result, but what this runtime is doing). Casting the constant will cause the compiler to convert the number and it does convert to the maximum positive number (0x7FFFFFFF).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top