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...
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.
The three basic boolean operators are: AND, OR, and NOT.
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.
The important operations performed in Boolean algebra are – conjunction (∧), disjunction (∨) and negation (¬).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With