1 |
>> >> I mean to really know C, |
2 |
>> >> that is, read a rigorous book such as "C: A Reference Manual" and be |
3 |
>> >> able to write portable programs with well-defined behavior. Speaking |
4 |
>> >> of well-defined behavior, do you know what happens when you cast a |
5 |
>> >> float to an int, and the float is too big to fit into the int? |
6 |
>> > |
7 |
>> > Did oyu try it yourself and see? |
8 |
>> |
9 |
>> The point is that the behavior in this situation is "undefined". It |
10 |
>> might do anything. Programming in C is different than programming in |
11 |
>> Python. |
12 |
> |
13 |
> Most likely the compiler will try to treat the float as an int and use the |
14 |
> first 4 bytes of the float, ignoring the rest. |
15 |
No, you misunderstood C. C, despite being lower level than (say) Java, |
16 |
does not view variables as typeless bit patterns. It views them as |
17 |
integers, real numbers, etc. |
18 |
So if you perform |
19 |
float real_number = 0.5; |
20 |
int integer = real_number; |
21 |
The value of "integer" will be 0; if C were to actually interpret the |
22 |
bit pattern of real_number as an integer, you would get 1056964608 |
23 |
(0x3f000000) - at least on my machine. That is not what C does, |
24 |
though. |
25 |
|
26 |
The real problem is when you type |
27 |
float real_number = 4e10; |
28 |
int integer = real_number; |
29 |
If your integer can only hold values up to 2^31 - 1 , the behavior of |
30 |
the above code is undefined. |
31 |
In a language like Python, everything either behaves as you intended, |
32 |
of throws an exception. |
33 |
This is why I say "In C, you must completely understand the behavior |
34 |
of every statement or function, and you *must* handle the possibility |
35 |
of errors". |
36 |
|
37 |
-- |
38 |
Software is like sex: it is better when it is free - Linus Torvalds |