?
? ????? PHP ??? ???? ??? ?? ??
邏輯運算符對其操作數(shù)應(yīng)用標(biāo)準(zhǔn)布爾代數(shù)運算。
Operator | Operator name | Example | Result |
---|---|---|---|
! | logical NOT | !a | the logical negation of a |
&& | logical AND | a && b | the logical AND of a and b |
|| | logical OR | a || b | the logical OR of a and b |
邏輯 NOT 表達式具有這種形式。
! expression |
---|
其中
expression | - | an expression of any scalar type |
---|
邏輯 NOT 運算符具有類型int
。它的值是0
如果表達式評估為一個比較不等于零的值。它的值是1
如果表達式計算出的值等于零。(如此!E
相同(0==E)
)。
#include <stdbool.h>#include <stdio.h>#include <ctype.h>int main(void){ bool b = !(2+2 == 4); // not true printf("!(2+2==4) = %s\n", b ? "true" : "false"); int n = isspace('a'); // zero if 'a' is a space, nonzero otherwise int x = !!n; // "bang-bang", common C idiom for mapping integers to [0,1] // (all non-zero values become 1) char *a[2] = {"nonspace", "space"}; printf("%s\n", a[x]); // now x can be safely used as an index to array of 2 ints}
輸出:
!(2+2==4) = falsenonspace
邏輯“與”表達式具有這種形式。
lhs && rhs |
---|
其中
lhs | - | an expression of any scalar type |
---|---|---|
rhs | - | an expression of any scalar type, which is only evaluated if lhs does not compare equal to 0 |
邏輯 AND 運算符具有類型int
和值,1
如果 lhs 和rhs 比較不等于零。它具有其他值0
(如果lhs或rhs或兩者都等于零)。
lhs評估后有一個序列點。如果lhs的結(jié)果等于零,則根本不評估rhs(所謂的短路評估)。
#include <stdbool.h>#include <stdio.h>int main(void){ bool b = 2+2==4 && 2*2==4; // b == true 1 > 2 && puts("this won't print"); char *p = "abc"; if(p && *p) // common C idiom: if p is not null // AND if p does not point at the end of the string { // (note that thanks to short-circuit evaluation, this // will not attempt to dereference a null pointer) // ... // ... then do some string processing }}
邏輯 OR 表達式具有表格。
lhs || rhs |
---|
其中
lhs | - | an expression of any scalar type |
---|---|---|
rhs | - | an expression of any scalar type, which is only evaluated if lhs compares equal to 0 |
如果lhs或rhs比較不等于零,則邏輯或運算符具有類型int
和值1
。它有價值0
否則(如果lhs和rhs比較等于零)。
lhs 評估后有一個序列點。如果lhs的結(jié)果不等于零,則根本不評估 rhs(所謂的短路評估)。
#include <stdbool.h>#include <stdio.h>#include <string.h>#include <errno.h>int main(void){ bool b = 2+2 == 4 || 2+2 == 5; // true printf("true or false = %s\n", b ? "true" : "false"); // logical OR can be used simialar to perl's "or die", as long as rhs has scalar type fopen("test.txt", "r") || printf("could not open test.txt: %s\n", strerror(errno));}
可能的輸出:
true or false = truecould not open test.txt: No such file or directory
C11 standard (ISO/IEC 9899:2011):
6.5.3.3 Unary arithmetic operators (p: 89)
6.5.13 Logical AND operator (p: 99)
6.5.14 Logical OR operator (p: 99)
C99 standard (ISO/IEC 9899:1999):
6.5.3.3 Unary arithmetic operators (p: 79)
6.5.13 Logical AND operator (p: 89)
6.5.14 Logical OR operator (p: 89)
C89/C90 standard (ISO/IEC 9899:1990):
3.3.3.3 Unary arithmetic operators
3.3.13 Logical AND operator
3.3.14 Logical OR operator