C not mathematically conforming?

: > Just out of curiosity, why does C not have a mathematically accurate mod (%)

: > and integer divide? It works for positive numbers just fine, of course, but

: > when you get into negative numbers, it does it the "common sense" way,

: which is

: > not the best way. (In my opinion, at least). The mathematical mod and div are

: > based upon the division algorithm, or a=bq+r, where q is an integer, and

: > 0<=r<b. a%b then should return r, and a/b should return q. However, when I do

: > something like -22%6, it gives -4, instead of 2. ( -22=6(-4)+2 ). This

: has been

: > annoying at times, especially when I was trying to implement a large integer

: > class, and I had to creat a special mod function for the large subtraction

: > function. Creating the new function wasn't that difficult, but it just seems

: > strange that C doesn't do it the standard mathematical way. I noticed

: that it's

: > the same in Pascal (at least Turbo Pascal). I tested the C in both Turbo C and

: > gcc/g++. Is this defined by ANSI by any change?

: There are two reasons:

: First, there is no universal agreement what (-5) / 3 should be. There are

: in my opinion two very reasonable definitions: One is that integer

: division should always round towards zero, the other is that integer

: division should always round down (another is that integer division should

: round according to the sign of the divisor). Actually I prefer rounding

: down if the divisor is positive, and have no opinion if the divisor is

: negative.

: Second, most processors have a divide instruction which gives the right

: results for positive numbers and works in some fixed way for negative

: numbers. If you divide x / y, the compiler doesnt know the signs of x and

: y. So if the standard defines what the results should be, and the

: processor happens to do it different, every single divide operation has to

: check the signs of the operands and do a lot of work. Actually, many

: processors I know do round towards zero, which is not the behavior we both

: would prefer. By leaving division of negative numbers implementation

: defined, these processors have a chance to use a single divide assembler

: instruction to implement the / operator.

: -- For email responses, please remove the last emm from my address.

--

*************begin r.s. response*****************

very interesting ...

cast to unsigned type may be

done directly ... or indirectly

...

directly ...

((unsigned) joevar )

indirectly ...

joeunsignedvar = joevar

( at least traditionally ... )

( then work with joeunsignedvar )

.

*************end r.s. response*******************

Ralph Silverman