Are the logical operators &&, || and ! really that simple?
What is the output of the following program?
int i=0; j=0; k=0; ++i||++j&&++k; #include <stdio.h> intmain() { int i=0; int j=0; int k=0; int s = 0; s = ++i||++j&&++k; printf("i = %d\n", i); printf("j = %d\n", j); printf("k = %d\n", k); printf("s = %d\n", s); return 0; }
Compile and run with GCC under Linux:
i = 1 j = 0 k = 0 s = 1
In logical operators, there is a concept of "short-circuiting.
||: Calculate from left to right, stop when the first condition is true, the whole expression is true, and the expression is false when all conditions are false.
&&: Operates from left to right. When the first condition that is false is encountered, the calculation is stopped, and the expression is false; the expression is true when all conditions are true.
In logical expressions, && has higher priority than ||, so the || operation is performed last, so the above logical operation is equivalent to:
++i||++j&&++k ==>> (++i) || (++j&&++k) ==>>> (true && ++i) || (++j&&++k)
That is, when && and || are mixed, the entire expression is regarded as a || expression, and the compiler starts to calculate the && expression from left to right. When the value of a && expression is true, the calculation stops, and the whole The expression evaluates to true.
Observe the following code and judge the output:
#include <stdio.h> int g=0; int f() { printf("Func f() is running.\n"); return g++; } intmain() { if( g || f() && f() ) { printf("In if statement.\n"); } printf("In main(): %d\n", g); return 0; }
g || f() && f() --> (true && g) || (f() && f())
So the output is:
Func f() is running. In main(): 1
logic! What exactly is it?
Observe the following code and judge the output:
intmain() { printf("%d\n", !0); printf("%d\n", !1); printf("%d\n", !100); printf("%d\n", !-1000); return 0; }Notably, logic! It only recognizes 0, and only knows that it returns 1 when it sees 0, so when it encounters other values that are not 0, it returns 0 directly.
So the result of running the above code is:
1 0 0 0
Summary: The logical expressions in the program follow the short-circuit rule;
In the mixed operation of && and ||, the entire expression is treated as the || expression, and the && (can be converted) is evaluated from left to right, and the || expression is finally evaluated.
Logical NOT! The operator only recognizes 0, and returns 1 when it encounters 0, otherwise it returns 0 directly.