The difference between signed and unsigned when doing `mod'

D

Dave Thompson

If signed int on your platform can hold all the values of an unsigned
short, 'a' and 'b' will be promoted to signed int for the subtraction.
Equivalent to: <snip>
Right.

The expression inside the parentheses evaluates to (int)-7. One of
the two possible correct values for -7 % 8 allowed prior to C99 is -7.
One of two correct values in C89/90 (and C95) and the only one in C99.
Prior to C89/90, I'm not sure if % was specified that precisely.
When you assign (int)-7 to an unsigned short, the behavior of unsigned
types with out of range values occurs. (int)-7 is converted to
USHRT_MAX - 7. For a 16-bit unsigned short, this is 0xffff - 7, which
equals 0xfff9.
(USHRT_MAX + 1) - 7, in this case 0x10000 - 7. In mathematically
correct arithmetic, not necessarily C or machine arithmetic.

<snip rest>
- David.Thompson1 at worldnet.att.net
 

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
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top