C arithmetic question.

C

Chad

Problem is here are several definitions of the modulo operation. They all
agree on what happens when operands are positive, but disagree what
happens when one of the operands is negative.

I'm not a standards-jockey, but i'd be interested what the experts have
to say.

Despite what some might claim on here, it just appears to me that the
C Standard isn't really (that far) out of sync with the "regular math".
 
T

Tim Rentsch

Ben Bacarisse said:
I'm not sure what you mean. % is odd in that it takes only integer
arguments yet it performs the usual arithmetic conversions designed to
establish "a common real type" for the operands.

The more I think about it, the odder % looks. It could be defined like
the shift operators to do only integer promotions and to yield a value
whose type is that of the promoted left operand. That would give it
more natural semantics, and, contrary to what I said above, would not be
odd at all.

The argument I would make (that is, defending the status quo) is
that % is an operation whose operand values come from the same
"field" or set of values, kind of a derived operation from
multiplication and addition. Shift operations, on the other
hand, have operands that come from very different domains; it
happens that in C both of those domains are (subsets of)
integers, but at some level that's just coincidence.

An example analogy: suppose our "field" were polynomials (over
a single variable) rather than integers. If P1 and P2 are
polynomials, it still makes sense to say

P1 % P2

but no sense to say

P1 << P2

whereas

P1 << N

could quite plausibly be defined, for example as P1 * X^N.

Considering the above, it makes sense for % to have the
same promotion rules as * and /.
 
K

Kleuske

The obligation of the programmer is to understand and consider the rules
of the language and the implementation and to code accordingly. This is
the contract between the language and the programmer. The programmer
breaks the contract at his own peril.

Good advice. Usually the peril is for the end user, though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,082
Messages
2,570,589
Members
47,212
Latest member
JaydenBail

Latest Threads

Top