GCC question

Talk about anything else you want

Moderator: BigEvilCorporation

Post Reply
Sh!ch
Interested
Posts: 11
Joined: Sun Jan 23, 2011 7:46 pm

GCC question

Post by Sh!ch » Sat Mar 26, 2011 1:55 pm

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:

Graz
Very interested
Posts: 81
Joined: Thu Aug 23, 2007 12:36 am
Location: Orlando, FL

Post by Graz » Sat Mar 26, 2011 2:25 pm

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.

Graz
Very interested
Posts: 81
Joined: Thu Aug 23, 2007 12:36 am
Location: Orlando, FL

Post by Graz » Sat Mar 26, 2011 2:56 pm

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).

Sh!ch
Interested
Posts: 11
Joined: Sun Jan 23, 2011 7:46 pm

Post by Sh!ch » Sun Mar 27, 2011 7:09 pm

&31 is just what I need.
Thanks Graz!

Post Reply