邏輯運算子
來自 cppreference.com
邏輯運算子對其運算元應用標準布林代數運算。
運算子 | 運算子名稱 | 示例 | 結果 |
---|---|---|---|
! | 邏輯非 | !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++ 文件中的 邏輯運算子
|