Search notes:

C: modulo operator %

% is the modulo operator. It evaluates to the rest of a division of two integer types, for example 7 % 4 evaluates to 3.

Operator precedence

It should be noted that the modulo operator has higher precedence than the not-operator (!). Thus, when testing a number if it divides without rest, the two integers need to be put in parantheses: ! (a % b). Without parantheses, this would test (!a) % b. If a is not 0, !a evaluates to 0, so ! a % b is true in that case.
This is demonstrated in the following simple program which tests if i is divisible by 5, once correctly and once faulty.
#include <stdio.h>

int main() {

   int i = 10;

//
// Probably as intended,
// prints 'yes'
//
   if (! (i % 5) ) {
      printf("yes\n");
   }
   else {
      printf("no\n");
   }

//
// Probably not as intended:
// prints 'no'
//
   if (! i % 5) {
      printf("yes\n");
   }
   else {
      printf("no\n");
   }
}
Github repository about-c, path: /language/operators/modulo.c
Because == has a lower precedence than %, the divisibility can also be tested with a % b == 0.

Index