P 的值出乎意料

The value oF P is unexpected

请问,您如何从技术上解释为什么 P =2 而不是 P=3。 (我在 Geany 上试过,它的值为 2)。

int main()
{
    int N = 10, P = 5, Q = 10;
    N = 5;
    P = 2;
    Q = ++N == 3 && P++ != 3;
    printf ("N=%d P=%d Q=%d\n", N, P, Q);
    return 0;
}

感谢您的回复。

因为在这种情况下 (P++ != 3) 您在实现 P3 之间的比较之后对值 (++) 求和。

如果您使用这种类型的比较 (++P != 3) 总和是比较之前的。

重点是(P++ != 3)(++P != 3)不一样。

C11 standard 状态:

6.5.13 Logical AND operator

4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated.

所以,基本上只有++N == 3在执行。而它的结果注定永远是false。因此,您的 AND 操作的右侧部分被跳过。

如评论中所述,这种行为称为 Short-circuit 评估。

Q = ++N == 3 && P++ != 3;

第一个表达式 (++N == 3) 为假,因此程序甚至不会执行第二个表达式。这种现象叫做Short Circuit Evaluation

/*
because in line
*/
Q = ++N == 3 && P++ != 3;

/*
you are not affecting any thing to P;

because true= true && true;
false= either both false or one of them is false
the compiler if it find any of the arguments false then it stops there and returns false.
it is mater of speed so if :
*/
Q=++N==3 && DoSomeThing();
/*
the function DoSomeThing() will never be called 
because ++N (which is now 6) do not equals 3;

but this will succeed obviously
*/

Q=++N==6 && DoSomeThing();