0

I did some research on GCC's % operator and it seems it doesn't calculate the correct value if it has a negative dividend. Well, I know all the relevant rules of GCC.

Anyway, -3%5 is

  • -3 by GCC and
  • 2 by Math

I'm using this macro now to correct this behaviour:

#define mod(M, N) (M>=0 ? M%N : (N-abs(M%N))%N)
#define mod2(M, N) (M%N>=0 ? M%N : M%N + N)

They both produces the right value, but look ugly and ineffective. Could you recommend any better (faster) way to do this calculation?

Thanks.

Daniel
  • 2,318
  • 2
  • 22
  • 53
  • 1
    gcc does what the C standard tells it to do, the behavior of % is a consequence of the behavior of / so that a=a/b*b+a%b, don't use macros, use static/inline functions instead. – Marc Glisse Jan 29 '17 at 10:51
  • 1
    Possible duplicate of [Fastest way to get a positive modulo in C/C++](http://stackoverflow.com/questions/14997165/fastest-way-to-get-a-positive-modulo-in-c-c) – Marc Glisse Jan 29 '17 at 10:59

0 Answers0