|
![](/i/fill.gif) |
In article <36c7a4da.0@news.povray.org> , "Nigel Stewart"
<nig### [at] eisa net au NOSPAM> wrote:
>>> DBL x = 2.0;
>>> becomes
>>> DBL x = (DBL) 2.0;
>>>
>>> Is there anything unreasonable or dangerous about doing this?
>>
>>It is unreasonable: DBL x = 2.0; is c acompletly legal and *well* readable
>>statement. DBL x = (DBL) 2.0 is less readable.
>
>But the meaning is more precise. I think the benefit of clarity and
>portability outweigh your concern - but that's entirely my opinion.
Hmm, there are no (and as far as I know have never been) portability
problems with floating point type casting. While I is might sometimes be
useful to do so in code like
SNGL sfp = 2.0;
DBL dfp = 8.0;
sf = (SNGL)(spf * dfp);
doing it for DBL x = (DBL) 2.0 is not only less readable, but even
redundant! It is defined in the ISO C++ standard that a type float value
will be *implicitly* converted to a type double value without loss of
precision. If you suggest doing DBL x = (DBL) 2.0 why not doing the same for
short x = (short)5, or long y = (long)7 because the native type of 5 and 7
would is assumed to be int by some compiler...
My opinion (and those who wrote the ISO C++ standard) is that writing
explicit conversion in these cases is redundant.
>While the first line says "I want 2.0 assigned to x", the second says
>"I knowingly want 2.0 converted to a DBL, and assigned to x".
I am wondering: What is the type of "2.0" for you? For me its type is the
largest floating point type supported by the implementation.
>For example, if you use a float as an intermediate result, treat it as a
>double later, and wonder why you're not getting the expected precision -
Yes, then you will have to check manually *every* cast because your compiler
can no longer tell you where the implicit conversion is happening! The goal
is to use as few casts as necessary, and casting *is* dangerous,for example
signed char f;
f = (signed char)(180); // Assumes sizeof(signed char) == 1 !!!
will no longer show an (optional) compiler warning because you explicitly
*forced* the compiler to do this while you have a chance to find the problem
writing
signed char f;
f = 180;
>the explicit cast will be something of a clue. Your preference is
>to be oblivious to truncation.
No, as the example above shows, it does exactly the opposite!
>It's a fine point, but I think it is more than just a platform/compiler
>quirk - in this case Microsoft have done something for a sound
>technical reason. (I wish they'd do so more often!)
Well, most compilers have this, but then they have it as an *option*, they
don't force these warnings!
And my opinion is that *standard* (Microsoft also worked in the ISO C++
commitee) behaviour should not show warnings by default. Doing so is a
misleading bug.
Thorsten
Post a reply to this message
|
![](/i/fill.gif) |