Readable code (Was: Re: [H-GEN] Which is better?)

Byron Ellacott bje at apnic.net
Wed Apr 28 23:35:07 EDT 2004


On Thu, 2004-04-29 at 10:51, Greg Black wrote:
> On 2004-04-29, Byron Ellacott wrote:
> > However, many languages don't really give you divide when you tell them
> > to '/' two values.  C, for example, does an integer divide, which
> > truncates its result.
> This is wrong[0].  For the arithmetic operators, the operands
> are subject to "the usual arithmetic conversions"[1].

My statement was incomplete.  I forgot to explicitly add, "when dealing
with integer types."  One of the solutions I provided, however, was
based on this fact: typecasting one operand will promote the operation
out of integer space.  Either (float)val or (double)val, or 100.0,
whatever doubles your boat.

I still prefer to do multiplications first, but that's a harmless relic
of habit.  As long as you're aware of the problem and take steps to
avoid it, the different solutions are all more or less equally
meritable, in my view.

> Furthermore, even for integer division, truncation is not the
> whole story.  If both integers are positive, it's correct.
> However, where either operand is negative, the result is
> implementation-defined[2].

I was unaware of this.  In general, I try to be careful with the
division operator, and either explicitly accept that I don't care about
rounding/truncating, or explicitly deal with it in a disambiguous way. 
I guess it's just never come up.

-- 
bje




More information about the General mailing list