C
C 语法

Logical operators

逻辑运算符

逻辑运算符对其操作数应用标准布尔代数运算。

OperatorOperator nameExampleResult
!logical NOT!athe logical negation of a
&&logical ANDa && bthe logical AND of a and b
||logical ORa || bthe logical OR of a and b

逻辑 NOT

逻辑 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) = false nonspace

逻辑 AND

逻辑“与”表达式具有这种形式。

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的结果等于零,则根本不评估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的结果不等于零,则根本不评估 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 = true could not open test.txt: No such file or directory

参考

  • C11 standard (ISO/IEC 9899:2011):