www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Can we drop cast from float to int ?

reply #ponce <ponce.remove-me adinpsz.org> writes:
I never knew exactly what the float-to-int C cast is supposed to do. 

float f = whatever();
int b = cast(int) f;


Does it truncate, floor or round ? Or even undefined, depending on the rounding
mode ? I just asked to 3 fellow programmers, it seems like i'm not the onlyone
to find this confusing.

Why should a destructive cast should be _that_ implicit anyway ?
Mar 22 2010
next sibling parent reply Trass3r <un known.com> writes:
 I never knew exactly what the float-to-int C cast is supposed to do.

 float f = whatever();
 int b = cast(int) f;


 Does it truncate, floor or round ?

I've never heard anything else but truncate. Rounding can thus be done with cast(int)(f + 0.5f).
Mar 22 2010
parent Lionello Lunesu <lio lunesu.remove.com> writes:
On 23-3-2010 7:59, Trass3r wrote:
 I never knew exactly what the float-to-int C cast is supposed to do.

 float f = whatever();
 int b = cast(int) f;


 Does it truncate, floor or round ?

I've never heard anything else but truncate. Rounding can thus be done with cast(int)(f + 0.5f).

or -0.5f when f < 0.0
Mar 22 2010
prev sibling parent reply Jesse Phillips <jessekphillips+D gmail.com> writes:
#ponce wrote:

 I never knew exactly what the float-to-int C cast is supposed to do. 

 float f = whatever();
 int b = cast(int) f;


 Does it truncate, floor or round ? Or even undefined, depending on the
rounding mode ? I just asked to 3 fellow programmers, it seems like i'm not the
onlyone to find this confusing.

 Why should a destructive cast should be _that_ implicit anyway ?

I've never considered anything but truncate. Also how is it implicit?
Mar 22 2010
parent reply #ponce <ponce.SPAMM adinpsz.org> writes:
 
 I've never considered anything but truncate.
 
 Also how is it implicit?

Well, ok it's not. It's just that it seems to me that it's useless and confusing. If it's really trunc, I have seen countless errors where it was used as floor.
Mar 23 2010
parent Jonathan M Davis <jmdavisProg gmail.com> writes:
#ponce wrote:

 
 I've never considered anything but truncate.
 
 Also how is it implicit?

Well, ok it's not. It's just that it seems to me that it's useless and confusing. If it's really trunc, I have seen countless errors where it was used as floor.

Maybe I've just never talked to enough programmers about it, but I've never talked to one who thought that it was anything other than truncate. I would have expected it to be mentioned in a decent C or C++ primer, but I haven't read any in a while, so I don't recally whether it's typical for it to be mentioned there. However, it is quite standard for C-derived languages to truncate when casting from float to integer. - Jonathan M Davis
Mar 23 2010