I have the following code:
NSInteger index1 = (stop.timeIndex - 1); //This will be -1
index1 = index1 % [stop.schedule count]; // [stop.schedule count] = 33
So I have the expression -1 % 33. This should give me 32, but is instead giving me 3… I’ve double checked the values in the debugger. Does anyone have any ideas?
C99 says in Section 6.5.5 Multiplicative operators (bold mine):
It says that
%is the remainder, and does not use the word “modulus” to describe it. In fact, the word “modulus” only occurs in three places in my copy of C99, and those all relate to the library and not to any operator.It does not say anything that requires that the remainder be positive. If a positive remainder is required, then rewriting
a%bas(a%b + b) % bwill work for either sign ofaandband give a positive answer at the expense of an extra addition and division. It may be cheaper to compute it asm=a%b; if (m<0) m+=b;depending on whether missed branches or extra divisions are cheaper in your target architecture.Edit: I know nothing about Objective-C. Your original question was tagged C and all answers to date reflect the C language, although your example appears to be Objective-C code. I’m assuming that knowing what is true about C is helpful.