逻辑运算符
来自 cppreference.cn
逻辑运算符对其操作数应用标准的布尔代数运算。
运算符 | 运算符名称 | 示例 | 结果 |
---|---|---|---|
! | 逻辑非 | !a | a 的逻辑非 |
&& | 逻辑与 | a && b | a 和 b 的逻辑与 |
|| | 逻辑或 | a || b | a 和 b 的逻辑或 |
内容 |
[编辑] 逻辑非
逻辑非表达式的形式为
! expression |
|||||||||
其中
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 一元算术运算符 (页码:89)
- 6.5.13 逻辑与运算符 (页码:99)
- 6.5.14 逻辑或运算符 (页码:99)
- C99 标准 (ISO/IEC 9899:1999)
- 6.5.3.3 一元算术运算符 (页码:79)
- 6.5.13 逻辑与运算符 (页码:89)
- 6.5.14 逻辑或运算符 (页码: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++ 文档 关于 逻辑运算符
|