Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C modulo operation rant

Name: OnePissedCustomer 2007-03-01 7:21 ID:Sj4eeSQv

So, the other day I was writing a loop that would index over a field backwards.
I had:
FRAME Frame_Tbl[MAX_FRAME]
int index = some value less than MAX_FRAME and greater than 0

I though it would be really clever to go index = (index - 1)%MAX_FRAME because I was, at that point, convinced that -1 % MAX_FRAME was equal to MAX_FRAME - 1. Ran the program. Segmentation fault. What the fuck?

Turns out that the C modulo operation, against all common logic, returns NEGATIVE values for a % b when a<0 and b>0. Just...Wow...
[INSERT PYTHON/PERL/RUBY/PHP/JAVA FANBOYISM HERE]

Name: Anonymous 2007-03-01 9:22 ID:Heaven

Never use % on negative values in C. The result may vary between compilers and architectures. Also, don't be "clever" when writing code unless you're in a programming competition where the only thing that matters is code speed.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List