Detecting inadvertent use of integer division
Don
nospam at nospam.com
Mon Dec 14 08:01:59 PST 2009
bearophile wrote:
> Don:
>>> In Pascal too (and OCaML, but the situation is different) they are separated. I think here having two operators is better,
>> Why?
>
> You are intelligent and expert so you must know my answer, so I fear yours is a trick question :-)
No, it's not a trick question. You've used Python extensively, I haven't.
> Two operators allow to reduce the need for casts (and rounding/truncation), and are more explicit, allowing the code to express its meaning better to people that come after the original programmer.
OK. I'm trying to get most of the benefits without needing an extra
operator.
What I wonder is, in what contexts is / ambiguous or difficult to read?
My feeling is that intentionally mixing integer division and
floating-point in the same expression is extremely rare. The effect of
my rule would be, that if you see an int anywhere, it's an integer
division; and if you see a floating point number anywhere, it's a
floating point division.
BTW, does Python allow integer division of floating point numbers?
eg, int_a = float_b // float_c; ?
(meaning cast(int)float_b / (cast(int)float_c); ).
My idea fails if:
* I'm completely wrong about the frequency of mixing integer division
with floating point. So the cost is high.
OR
* Inadvertant integer division commonly occurs in things like int a =
b/c; (which would mean that I'm wrong in assuming it's primarily an
implicit casting problem). If the benefit is low, it's not much use.
OR
* There's something I didn't think of. Which is quite probable <g>.
> You can put them in the middle of a long expression, so you know what it's happening in the middle of it. This is useful for programming newbies too.
>I know there's a C translation of every usage of those two operators, but this is beside the point: even if the Laws of C language are sometimes explicit, sometimes they are not so natural and easy to remember, because normal people are not computers.
Yeah, I agree. C never errs on the side of caution <g>. Much of D
involves tightening things up considerably.
More information about the Digitalmars-d
mailing list