2012-07-23 32 views
5

條件表達式如那些涉及& &||,他們總是評估爲0或1?或者對於真實情況,除1之外的數字是可能的?我在問,因爲我想分配一個像這樣的變量。條件表達式總是在C中評估爲0或1嗎?

int a = cond1 && cond2; 

我想知道是否應該做下面的事情。

int a = (cond1 && cond2)? 1:0; 
+0

實際上,您的主要要求是什麼?爲什麼你要分配這些變量? – 2012-07-23 18:14:22

回答

14

邏輯運算符(&&||,和!)所有取值爲10

C99§6.5.13/ 3:

&&操作者應得到1如果兩個操作數的比較不等於0;否則,產生0。結果爲int

C99§6.5.14/ 3:

||操作者應得到1如果任一操作數的比較不等於0;否則,產生0。結果爲int

C99 6.5.3.3/5:

邏輯非操作者!的結果是0如果操作數的值不相等的比較來01如果其操作數的值進行比較等於0。結果爲int。表達式!E相當於(0 == E)。

+0

(我沒有C11方便的副本,但我確信邏輯運算符的規格沒有改變。) – 2012-07-23 17:57:02

0
'&&' 
    The logical-AND operator produces the value 1 if both operands have nonzero 
    values. If either operand is equal to 0, the result is 0. If the first operand of a 
    logical-AND operation is equal to 0, the second operand is not evaluated. 

'||' 
     The logical-OR operator performs an inclusive-OR operation on its operands. 
    The result is 0 if both operands have 0 values. If either operand has a nonzero 
    value, the result is 1. If the first operand of a logical-OR operation has a nonzero 
    value, the second operand is not evaluated. 

邏輯與和邏輯或表達式的操作數從左向右進行評估。如果第一個操作數的值足以確定操作的結果,則不評估第二個操作數。這被稱爲「短路評估」。第一個操作數之後有一個序列點。

謝謝,:)

+2

而這並不回答這個問題。 – 2012-07-23 18:19:39