L
Luca Forlizzi
hello I try to "resurrect" the thread "was: "mod operator for signed
integers"" because I tried to find the answers to the following
questions posed by Tim Rentsch
it should be (INT_MAX-1)+UINT_MAX, which is greater then the maximum
value representable in an unsigned int. So the expression can exhibit
overflow
this confuses me, since at first glance I only see one possibility,
unsigned int.
Indeed, m and INT_MAX have type int. Maybe UINT_MAX is the tricky one:
if an int can
represent all values of unsigned int, UINT_MAX has int type (by
5.2.4.2.1 p1). So in this case the whole expression has type int,
while in all other cases it has type unsigned int, because of the
usual arithmetic convertions
the proposed solution to the OP's question was:
m < 0 ? n-1 - -(m+1)%n : m%n
I tried to prove that it's correct (for the case m<0) but I did not
succeed
yet. My difficulty is maybe that I am unable to find an analitical
definition
of what result the OP was expecting. Could someone provide more hints?
LF
integers"" because I tried to find the answers to the following
questions posed by Tim Rentsch
If we have 'int m;' and 'unsigned n;', with m in [ INT_MIN .. -1 ]
and n in [ 1 .. UINT_MAX ], consider the expression
(m + INT_MAX) + n
Question 1: What is the maximum value of this expression,
considered as a mathematical expression?
it should be (INT_MAX-1)+UINT_MAX, which is greater then the maximum
value representable in an unsigned int. So the expression can exhibit
overflow
Question 2: Considered as a C expression, what is the
type of the expression? (Hint: there is more than one
possibility.)
this confuses me, since at first glance I only see one possibility,
unsigned int.
Indeed, m and INT_MAX have type int. Maybe UINT_MAX is the tricky one:
if an int can
represent all values of unsigned int, UINT_MAX has int type (by
5.2.4.2.1 p1). So in this case the whole expression has type int,
while in all other cases it has type unsigned int, because of the
usual arithmetic convertions
Question 3: Have you tried working through the solution
that was posted, to see how it works?
the proposed solution to the OP's question was:
m < 0 ? n-1 - -(m+1)%n : m%n
I tried to prove that it's correct (for the case m<0) but I did not
succeed
yet. My difficulty is maybe that I am unable to find an analitical
definition
of what result the OP was expecting. Could someone provide more hints?
LF