code questions.

me22 me22.ca@gmail.com
Tue Jun 3 01:59:00 GMT 2008


On Mon, Jun 2, 2008 at 9:48 PM, Scott Phuong <mycleanjunk@gmail.com> wrote:
>
>        unsigned short a;
>        unsigned short b;
>
>        a = 0xFFFF;
>        b = 0x3FC;
>
>        a = (a + 1) % b;
>        printf ("A is 0x%x\n", a);
>        // I expect the answer to be 0 and it is not! It is 0x100. Why is this?
>

I bet if you did

    ++a; a %= b;

you'd get 1.

I don't know the exact rules, but 1 is an int, so a+1 will give you
(int)a + 1, which will be 0x10000, which when modded by (int)b will
not be 0.

I'd have to read up on integral promotion to be sure, but I think the
only way is to add an explicit cast.

    a = (unsigned short)(a+1) % b;

(If you want to keep it one expression, and of that form.  ++a, a %=b;
is possible, as mentioned, and a = ( (a+1) & 0xFFFFu ) % b would also
work.)

HTH,
~ Scott



More information about the Gcc-help mailing list