Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 802
rolory Avatar asked Nov 20 '15 16:11

rolory


People also ask

What do Boolean expressions do?

A Boolean expression is a logical statement that is either TRUE or FALSE . Boolean expressions can compare data of any type as long as both parts of the expression have the same basic data type. You can test data to see if it is equal to, greater than, or less than other data.

What are the 3 Boolean expressions?

The three basic boolean operators are: AND, OR, and NOT.

Is == a Boolean expression?

A boolean expression is an expression that evaluates to a boolean value. The equality operator, == , compares two values and produces a boolean value related to whether the two values are equal to one another.

What are the symbols used for Boolean expressions?

The important operations performed in Boolean algebra are – conjunction (∧), disjunction (∨) and negation (¬).


1 Answers

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.

like image 184
fuz Avatar answered Sep 30 '22 03:09

fuz