2015-10-05 50 views
-3

请问,您如何解释为什么P =2而不是P=3。 (我在Geany上试了一下,它的值为2)。P的值是意想不到的

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; 
} 

感谢您的回复。

+0

&&有什么问题?我该如何精确地向C语言初学者解释这个问题? 我试图做这样的反转Q = ++ N!= 3 && P ++ == 3 所以我在P. – OntoBLW

回答

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

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

2

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

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

问题是(P++ != 3)(++P != 3)不一样。

+0

中得到3虽然是正确的,但这不是正确的答案。我的意思是,当用((++ P!= 3;)替换'(P ++!= 3;)'时获得同样的结果'请参阅其他答案。 –

1

C11 standard状态:

6.5.13逻辑与运算

4不同的是按位二进制&运算符,& &运营商保证左到右的评价; 评估第一个操作数后有一个序列点。如果第一个操作数 的值等于0,则不计算第二个操作数。

所以,基本上只有++N == 3正在执行。结果总是注定是false。因此,您的AND操作的右侧部分只是略过。

正如评论中指出的那样,这种行为称为Short-circuit评估。

0
/* 
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();