Why is x%3 and x%3==0 not the same?


#1
#include <stdio.h>

int main (int argc, const char * argv[])
{
    int x;
    for (x = 99; x >=0 ; x--3) {
       
        if (x%3) {
            continue;
        }
        
        
        printf("%d.\n", x);
    
        if (x%5 ==0) {
            printf("found one.\n");
        }
    
   }
return 0;
}

This solution works the same as it would if I was to change x-- to x-=3 in the for statement.
How do I read x%3? is it asking for multiples of 3 with no modulus? because x%3 == 0 asks for no modulus but both output two very different sets of results…
I hope my question makes sense…


#2

In C and Objective-C, 0 is equivalent to false in a true/false context, whereas any other number evaluates to true.

x%3 returns a remainder, right? 5%3 evaluates to 2, 4%3 evaluates to 1, 6%3 evaluates to 0.

So, counterintuitively, 5%3 is a true statement because 5 is not evenly divisible by 3, and thus there’s a non-zero value for that expression.

12%3 is a false statement because it evaluates to 0.

Examples to illustrate:

if (1) {
  // This code will execute
}

if (-42) {
  // This code will execute
}

if (0) {
  // This code will NOT execute
}

if (5 % 3) {
  // This code will execute because 5 % 3 is 2, and 2 is not 0
}

#3

thank you for clearing that up for me :slight_smile: