C++の剰余の定義

例えば負の数の絡むC++の剰余の計算結果は?そもそもC++の剰余演算の定義は。 調べたところstackoverflowに回答がありました。
http://stackoverflow.com/questions/7594508/modulo-operator-with-negative-values

C++03では実装依存のようですが、C++11では以下のように定義されているようです。

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

除算演算子を適用した残り(言葉足らずですが…)を剰余と定義しています。計算手順は、

(-7/3) => -2
-2 * 3 => -6
-7%3 => -7 - (-6) => -1

(7/-3) => -2
-2 * -3 => 6
7%(-3) => 7-6 => 1

のようになります。
このように剰余が負の値になることがあるのですね。

また、C++11では

-10%7 =>-3

のような計算結果が保証されますが、C++03では実装依存なので例えば

-10%7 => 4

のようになる可能性があるかもしれません。
ちなみにこの計算結果はperl5, ruby2.0, python2などでは4になりました。普段他言語を使っているプログラマにとっては落とし穴になりそうですね。

剰余としてどれを採るかには選択の余地があるという話
http://research.microsoft.com/pubs/151917/divmodnote.pdf