1 |
On Wed, Oct 29, 2008 at 3:16 AM, Alan McKinnon <alan.mckinnon@×××××.com> wrote: |
2 |
> On Wednesday 29 October 2008 00:55:42 Jorge Peixoto de Morais Neto wrote: |
3 |
>> >> I mean to really know C, |
4 |
>> >> that is, read a rigorous book such as "C: A Reference Manual" and be |
5 |
>> >> able to write portable programs with well-defined behavior. Speaking |
6 |
>> >> of well-defined behavior, do you know what happens when you cast a |
7 |
>> >> float to an int, and the float is too big to fit into the int? |
8 |
>> > |
9 |
>> > Did oyu try it yourself and see? |
10 |
>> |
11 |
>> The point is that the behavior in this situation is "undefined". It |
12 |
>> might do anything. Programming in C is different than programming in |
13 |
>> Python. |
14 |
> |
15 |
> Most likely the compiler will try to treat the float as an int and use the |
16 |
> first 4 bytes of the float, ignoring the rest. |
17 |
Float is 4 bytes; the questions should be reworded s/float/double/g |
18 |
|
19 |
But somehow, SSE version or fisttp (or whatever) doesn't set CF/OF on |
20 |
overflow, the returned int is simply (1 << 31) ^ (1 << 31 - 1) |
21 |
> This is insane though. I cannot think of any reason why one would ever want to |
22 |
> treat the first 32 bits of a float as an int. It's not like you are casting a |
23 |
> long to an int which can make sense - just discard the high bits. |
24 |
|
25 |
> I reckon the standard would say this is undefined. Most compiler would bomb |
26 |
> out with a compile error but give you an obscure flag to proceed anyway. If |
27 |
> you want to commit suicide, C is quite happy to pass you the pills as long s |
28 |
> you ask nicely |
29 |
gcc does this without errors |
30 |
Code [x86/64 only]: |
31 |
#include <stdio.h> |
32 |
#include <math.h> |
33 |
#include <stdint.h> |
34 |
int main() { |
35 |
double f = 1.5e99; |
36 |
int i = (int)f; |
37 |
uint16_t z; |
38 |
asm("pushf; popw %0;" : "=r"(z)); |
39 |
printf("%d %d %d\n", i, (z & (1 << 11)), (z & 1) ); |
40 |
return 0; |
41 |
} |
42 |
|
43 |
|
44 |
In short, your mileage shall vary, so sayeth the standard. |
45 |
> -- |
46 |
|
47 |
-- |
48 |
Andrey Vul |
49 |
|
50 |
A: Because it messes up the order in which people normally read text. |
51 |
Q: Why is top-posting such a bad thing? |
52 |
A: Top-posting. |
53 |
Q: What is the most annoying thing in e-mail? |