On Fri, 16 Dec 2005 21:05:16 -0800, Thomas Matthews
<> wrote in comp.lang.c:
> Hi,
>
> We had an applications guy use a {signed} int and the operator % in an
> embedded system. None of us could figure out if this was a valid
> operation, and if so, what is sign of the result?
>
> In searching the newsgroup, I found an article stating that the
> operator % is a "remainder operator" not a modulus operator.
> Is this true? If so, is the result ever negative?
>
> {Posted to comp.lang.c and comp.lang.c++ because it pertains
> to both languages.}
The statement above raises a serious issue, at least as far as posting
in comp.lang.c is concerned. As far as the C language is concerned,
C++ does not exist. Actually, I exaggerate. The C language and
standard take no notice, nor any responsibility, for languages "based
on C" or that adopt part of C's syntax. As far as the C standard, and
comp.lang.c are concerned, there is no "Objective C", "Java", "C#",
"D", and who knows how many others.
Where did I exaggerate? The C language and its ISO standard do barely
acknowledge that C++. It is mentioned in no less than four footnotes
in the current C standard, basically at the request of the C++
standard committee. And the C standard specifically forbids a
conforming C implementation from defining a macro "__cplusplus". So
since 1999, C acknowledges that C++ exists.
Why am I making such a point of this? Because C++ adopts part of, but
not all of, an earlier (1995) version of the C standard, and makes
subtle changes to other parts, some of them quiet and likely to trap
the unwary.
So here in comp.lang.c, the only answer is what the C standard
requires and/or allows to happen in C. Whether C++ requires/allows
the same, or something different, is quite off-topic here.
>
> Given:
> signed int A;
> signed int B;
>
> What are the signs of the result column below
> where Result = A % B; /* B != 0, A != 0 */?
> A B Result
> ----------------------------------------------
> positive, > B positive
> positive, < B positive
> negative, magnitude < B positive
> -2 * B positive
> positive, magnitude > B negative
> positive, magnitude < B negative
> negative, magnitude < B negative
> negative, magnitude > B negative
As for the C language, the operation is valid regardless of the signs
of the operands, as long as B is not 0.
Here is exactly what the C standard guarantees for A % B given that A
and B are signed int:
A positive or 0, B positive: result positive or 0.
Any other case: result positive, negative, or 0.
The sign of a non-zero result of the % operator when either or both of
the operands is negative is implementation-defined.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html