The REAL problem with C.

Andrew Koenig ark at alice.UucP
Tue Feb 18 15:32:18 AEST 1986


> The real problem of course isn't that the % operator was definded
> correctly or incorrectly, the problem is that it is intentionally
> poorly defined in C.  The expression -5%2 will be positive on some
> implementations, and negative on others, but in both cases the answer
> will be "correct".
>
> As a programmer, I don't really care which way the result turns out.
> But I do care that I get the same result all the time.  It would be
> wonderful if the definition of C could guarantee this consistancy,
> but it doesn't, any more than it guarantees that (char) is signed
> or unsigned, or that intvar>>5 is a logical or an arithmetic shift.

Here's a counter-argument.

In areas where various machines differ in detail, C generally tries
to give you whatever is most efficient on your machine; if you care
about a particular definition it is up to you to implement it to
the extent you need it.

Thus, C does not guarantee any particular number of bits in an
int, beyond those needed for subscripts.  It does not guarantee
the result when you say n>>k unless k >= 0 and k is less than the
number of bits in n.  And so on.

Division is treated similarly.  You are guaranteed that whenver the
mathematical result of an integer division can be represented
exactly as an integer, that's what you get.  You are guaranteed
that divide will round toward 0 when both operands are positive.
And you are guaranteed that the % operator gives you enough information
that you can implement whatever definition of / you like and do so
portably.

It's no different from how C handles these other issues.  Sure, C could
have been defined more rigidly.  But it wasn't.



More information about the Comp.lang.c mailing list