Page 1 of 1

GCC question

Posted: Sat Mar 26, 2011 1:55 pm
by Sh!ch
I'm going mad. Anyone can tell me why following C parts are working differently?

Code: Select all

1)
unsigned char smth;
smth=0;
smth--;
smth%=32;
 smth equals 31 // Just what I want

2)
unsigned char smth;
smth=0;
smth=(smth-1)%32;
 smth equals 255 // Why?
Is this expected behavior? :shock:

Posted: Sat Mar 26, 2011 2:25 pm
by Graz
From only this information, it looks like a compiler bug. Nothing %32 should be >= 32 by definition. 68K gcc I assume? What version of the compiler are you using? Can you post the disassembly (use -fsave-temps or objdump -S).

As a workaround, you could do smth=(smth-1)&31. It's more efficient anyway.

Posted: Sat Mar 26, 2011 2:56 pm
by Graz
Strike that. Not enough coffee.

Your (smth - 1) is executed using integers in C. -1 % 32 = -1, which when re-read as unsigned char is 255. The compiler is correct.

You could try (unsigned int)(smth - 1) % 32. However, the solution using & 31 is probably what you mean anyway (as in, you want the low 5 bits).

Posted: Sun Mar 27, 2011 7:09 pm
by Sh!ch
&31 is just what I need.
Thanks Graz!