[Tutorial] Pipes Part 3 - Additional Information

Modulus in C / C++


A modulus (modulo, mod) is simply the remainder when dividing one number by another. When we divide 7 by 2 the result is 3 with 1 remainder. In C / C++ the operand % returns the modulus between two numbers, for example:

printf("%i \n", 7 % 2);         >> Outputs ‘1’.

One ‘gotcha’ with the modulus operation is that it returns the modulus using the same sign as the dividend. The sign of the divisor is irrelevant. The examples below shows this in action:

printf("%i \n", 7 % 2);         >> Outputs ‘1’.
printf("%i \n", -7 % 2);       >> Outputs ‘-1’.
printf("%i \n", 7 % -2);       >> Outputs ‘1’.
printf("%i \n", -7 % -2);     >> Outputs ‘-1’.

Consider the function below. It tests to see if a number is odd by checking the modulus is one. Of course, this will fail if the numberToTest is negative.

bool isAnOddNumber(int numberToTest) {
    return numberToTest % 2 == 1;
}

Changing the function to test for a non-zero number - a one or a negative one – accounts for both positive or negative inputs.

bool isAnOddNumber(int numberToTest) {
    return numberToTest % 2 != 0;
}
1 Like