The REAL problem with C.

Ray Butterworth rbutterworth at watmath.UUCP
Tue Feb 18 04:52:00 AEST 1986


I wonder how many tens of thousands of dollars of time and resources
have been wasted recently by all of these complaints and discussions
about what the % operator should do.

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.

X3J11 (April 85) says this about the "/" division operation:
    If either operand is negative, whether the result of the
    / operator is the largest integer less than the true quotient
    or the smallest integer greater than the true quotient is
    implementation defined

Now that is an almost totally useless definition.  All it says
is that the answer will be wrong by less than 1.  I find it hard
to imagine someone deliberately implementing a division operator
that was out by 1 or more from the correct answer.  e.g. -5/2
could be -2 or -3, but -1 and -4 are wrong.

Given two arbitrary integers, a and b, I'd like to find their
quotient and the non-negative remainder.  The following is the
best that I could come up with:
    q=a/b;
    r=a-q*b;
    if(r<0){
        if(b<0) {r-=b; q+=1;}
           else {r+=b; q-=1;}
    }
Now that seems like a lot of work to go to just to be portable
across different compilers (possibly on the same hardware).
And notice that it doesn't use the % operation since that is
just as poorly defined as /.

If the standard said "a%b" will always have a positive value,
(or always the same sign as a (or as b), or whatever) then some
people would say that that is a good standard and some that that
is a bad standard.  But I don't see how anyone can say anything
good about a standard which deliberately avoids the issue.



More information about the Comp.lang.c mailing list