逻辑运算符
来自 cppreference.cn
逻辑运算符对其操作数应用标准布尔代数运算。
运算符 | 运算符名称 | 示例 | 结果 |
---|---|---|---|
! | 逻辑非 | !a | a 的逻辑非 |
&& | 逻辑与 | a && b | a 和 b 的逻辑与 |
|| | 逻辑或 | a || b | a 和 b 的逻辑或 |
目录 |
[编辑] 逻辑非
逻辑非表达式的形式为
! expression |
|||||||||
其中
表达式 | - | 任何标量类型的表达式 |
逻辑非运算符的类型为int。如果expression求值为与零不相等的值,则其值为0。如果expression求值为与零相等的值,则其值为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'); // non-zero if 'a' is a space, zero otherwise int x = !!n; // "bang-bang", common C idiom for mapping integers to [0,1] // (all non-zero values become 1) char *a[2] = {"non-space", "space"}; puts(a[x]); // now x can be safely used as an index to array of 2 strings }
输出
!(2+2==4) = false non-space
[编辑] 逻辑与
逻辑与表达式的形式为
lhs && rhs |
|||||||||
其中
lhs | - | 任何标量类型的表达式 |
rhs | - | 任何标量类型的表达式,仅当lhs与0不相等时才求值 |
逻辑与运算符的类型为int,如果lhs和rhs都与零不相等,则其值为1。否则(如果lhs或rhs或两者都与零相等),其值为0。
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 } }
[编辑] 逻辑或
逻辑或表达式的形式为
lhs || rhs |
|||||||||
其中
lhs | - | 任何标量类型的表达式 |
rhs | - | 任何标量类型的表达式,仅当lhs与0相等时才求值 |
逻辑或运算符的类型为int,如果lhs或rhs与零不相等,则其值为1。否则(如果lhs和rhs都与零相等),其值为0。
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 标准 (ISO/IEC 9899:2011)
- 6.5.3.3 一元算术运算符 (p: 89)
- 6.5.13 逻辑与运算符 (p: 99)
- 6.5.14 逻辑或运算符 (p: 99)
- C99 标准 (ISO/IEC 9899:1999)
- 6.5.3.3 一元算术运算符 (p: 79)
- 6.5.13 逻辑与运算符 (p: 89)
- 6.5.14 逻辑或运算符 (p: 89)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 3.3.3.3 一元算术运算符
- 3.3.13 逻辑与运算符
- 3.3.14 逻辑或运算符
[编辑] 另请参阅
常见运算符 | ||||||
---|---|---|---|---|---|---|
赋值 | 递增 递减 |
算术 | 逻辑 | 比较 | 成员 访问 |
其他 |
a = b |
++a |
+a |
!a |
a == b |
a[b] |
a(...) |
[编辑] 另请参阅
C++ 文档中的 逻辑运算符
|