Search code examples
cif-statementboolean-expression

What does '-' do as a boolean expression


What I generally wanted to do is to check when (x-3) > i.
I got the following code:

int main()
{
    int x = 10, i;

    for(i = 0; i < 15; i++) {
        if(x-3)
            printf("%d, ", x);

        x--;
    }

    return 0;
}

I accidentally wrote (x-3) instead of (x-3 > i), and I got these results:

10, 9, 8, 7, 6, 5, 4, 2, 1, 0, -1, -2, -3, -4,

The number 3 is missing. I understood that it is something that somehow connected to the x-3 expression, but I haven't find a clear answer yet in Google..

Does anyone have an idea? Thanks...


Solution

  • In C, an expression is considered to be false if its value is 0 (zero), all other values are considered to be true. Thus, the expression x - 3 is true if and only if x != 3 which is why you see 3 being skipped in your loop.

    This also applies to pointers: The null pointer is false, all other pointers are true. You are going to see code like this:

    if (some_pointer) {
       do_something();
    }
    

    Here do_something(); is only executed if some_pointer is not the null pointer. Similarly, null pointer checks often look like this:

    if (!some_pointer) {
        fprintf(stderr, "Encountered a null pointer\n");
        abort();
    }
    

    Because the logical not operator applied to a pointer yields 1 (true) for the null pointer and 0 (false) for all other pointers.


     More pedantically, it is considered to be false if and only if it compares equal to 0. There is a subtle difference in this wording as e. g. the null pointer may not have the value 0 but it compares equal to the integer literal 0.