1 |
>> The real problem is when you type |
2 |
>> float real_number = 4e10; |
3 |
>> int integer = real_number; |
4 |
>> If your integer can only hold values up to 2^31 - 1 , the behavior of |
5 |
>> the above code is undefined. |
6 |
>> In a language like Python, everything either behaves as you intended, |
7 |
>> of throws an exception. |
8 |
>> This is why I say "In C, you must completely understand the behavior |
9 |
>> of every statement or function, and you *must* handle the possibility |
10 |
>> of errors". |
11 |
> |
12 |
> The line: |
13 |
> int integer = real_number; |
14 |
> will produce a warning. (or an error if you are smart enough to |
15 |
> compile with -Werror) |
16 |
It seems you did not get the point. To attribute a floating point |
17 |
number to an integer variable is perfectly valid, depending on the |
18 |
specific program. The compiler normally does not even warn about |
19 |
this, as this is perfectly valid (from my testing, the compiler only |
20 |
warns if you are using gcc 4.3, and specify -Wconversion, an option |
21 |
that is not included in -Wall and not even in -Wextra). |
22 |
|
23 |
So erase this *wrong idea* that attributing floating-point value to an |
24 |
integer variable is invalid or even just unwise. There is nothing |
25 |
generally wrong with it. |
26 |
|
27 |
The point is: in certain situations, the behavior is well-defined and |
28 |
unsurprising. What happens, though, if (for example) the value of the |
29 |
floating-point variable is too big for the int? |
30 |
In a forgiving language, you would either have a sensible behavior |
31 |
(such as the int receiving a INT_MAX value) or an error. In C the |
32 |
behavior is *undefined*. |
33 |
|
34 |
Got the point? In C, you *must* know what you are doing, and *must* |
35 |
handle the possibility of errors. If not, your program is not even |
36 |
garanteed to crash; it can, after an error, go on working |
37 |
(erratically), possibly damaging user data or yielding subtly wrong |
38 |
results without any warning. |
39 |
|
40 |
-- |
41 |
Software is like sex: it is better when it is free - Linus Torvalds |