What makes "-" like a boolean expression
What I usually wanted to do was 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 got these results:
10, 9, 8, 7, 6, 5, 4, 2, 1, 0, -1, -2, -3, -4,
Number 3 is missing. I realized this had something to do with the x-3 expression, but I haven't found a clear answer on Google yet.
Does anyone have an idea? Thanks...
In C, an expression is considered false if its value is 0 (zero), & dagger; all other values ββare considered true. Thus, the expression x - 3 true if and only if x != 3 , so you see that 3 skipped in your loop.
This also applies to pointers: a null pointer is false, all other pointers are true. You will see the following code:
if (some_pointer) { do_something(); } Here do_something(); executed only if some_pointer not a null pointer. Similarly, checking a null pointer often looks like this:
if (!some_pointer) { fprintf(stderr, "Encountered a null pointer\n"); abort(); } Since the logical operator applied to the pointer gives 1 (true) for the null pointer and 0 (false) for all other pointers.
& dagger; & emsp. More pedantically, it is considered false if and only if it is compared to 0 . There is a subtle difference in this wording, like e. & Thinsp; g. a null pointer may not have a value of 0, but it is compared with the integer literal 0 .
It just means a lookup operator. :)
According to the C standard (6.8.4.1 if statement)
2 In both forms, the first subset is true if the expression is compared not equal to 0 . In another embodiment, the second substitution is performed if the expression is compared with 0. If the first reinforcement is reached through the label, the second is not executed.
In this if statement
if(x-3) expression x - 3 always evaluates to a nonzero value, unless x is 3 .
Therefore, when x not equal to 3 , this statement
printf("%d, ", x); runs and displays the current value of x .
When x is 3 , this statement is skipped.
The result clearly demonstrates this.
10, 9, 8, 7, 6, 5, 4, 2, 1, 0, -1, -2, -3, -4 ^^^ 3 is absent The loop repeats 15 times, but only displays 14 x values. An x value of 3 is skipped due to the expression in the if statement.
Morning friend! Therefore, if an expression (expression) follows only when the expression is true. In C (and C ++ and elsewhere) 0 = false and all other numbers = true (the exception is null )
Therefore, when x = 3 , x-3 = 0 . So, if(x-3) equated to false. Thus, the program never reaches the print statement. A.
As you go, you decrease x from 10, so that in the end x will be equal to 3, after which you will not receive print instructions. A.
Hope this helps!