Detecting inadvertent use of integer division

Don nospam at nospam.com
Tue Dec 15 11:41:10 PST 2009


Bob Jones wrote:
> "Don" <nospam at nospam.com> wrote in message 
> news:hg7gbm$1vln$1 at digitalmars.com...
>> Bob Jones wrote:
>>> "Don" <nospam at nospam.com> wrote in message 
>>> news:hg5nkk$1n37$1 at digitalmars.com...
>>>> 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.
>>> Having made the switch from Delphi to C++ a few years ago I ran into this 
>>> alot. I dislike that I have to litter my arithmetic expresions with casts 
>>> in order to get the division operator to do what I want it to. And I 
>>> suspect all of those who are used to having seperate intdiv & fltdiv 
>>> operators will agree.
>> Your arithmetic expressions would only become "littered with casts" if you 
>> regularly use integer division inside floating-point expressions.
>> Personally, I cannot recall *ever* having intentionally used integer 
>> division inside a floating point expression. (I've seen inadvertent uses 
>> of it, plenty of times).
> 
> I grepped around 60 instances of
> 
> double y = a / double(b);
> 
> In my last project. That's what I'm talking about. Where you have to cast 
> either top or bottom to float in order to get the division operator to do 
> float division of two int operands.

OK, I misunderstood you. You're completely right. At least my proposal 
won't let them slip through silently. I don't think we can do anything 
else without silently breaking C compatibility.

> There's also the (perhaps MSVC specific) issue that I have to cast doubles 
> to floats to get rid of the loss of precision warning message. It's a usuful 
> warning on ints, but for floats it's completely redundant imo.
> 
> 
>>> The fact that adding a specific intdiv operator would not only avoid more 
>>> casting, but remove the the need for casting in a lot of existing cases
>> I bet there are negligible cases where casting is required.
> 
> I didnt find any instances of an expresion containg intdiv being assigned to 
> a float, so yeah, that is rare. But not the case where you have two ints and 
> want the actual division done in float.



More information about the Digitalmars-d mailing list