I was making a C program where I wanted to make a function which takes in an "n" integer, and returns the number of divisors it has.
int divisors(int n) {
int amount = 0;
for(int i = 0; i <= n; i++) {
printf("%d mod %d = %d\n", n, i, n % i);
if(n % i == 0) {
amount++;
}
}
return amount;
}
The printf is obviously for debugging. The part of the code that would cause problems is that the loop starts with 0, meaning that in the first iteration, the program would have to print N mod 0. However, I tested out the function by just assigning some int a to this function with the input of 8 in main(), and the program prints this:
8 mod 0 = 8
8 mod 1 = 0
8 mod 2 = 0
8 mod 3 = 2
8 mod 4 = 0
8 mod 5 = 3
8 mod 6 = 2
8 mod 7 = 1
8 mod 8 = 0
So 0 modulus is being run with no problem, and returns n instead. The interesting part is if I explicitly tell the program to printf("%d", 8 % 0);
then I get the error I expect. So does anyone know why n mod 0 runs without errors in C when it is in loops?
NOTE: The program is compiled with GCC and is not even throwing any warnings/errors when compiling.
EDIT: Added gcc --version.
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1 Apple clang version 13.0.0 (clang-1300.0.29.3) Target: arm64-apple-darwin20.6.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin