C++替代關鍵詞(and,or,not)

下列例子用到了C++的關鍵詞 andnot,雖然這種作法比較少用,但它可讀性比 ||!會好不少。
bool isOk = false;
int i = 1;
if (i < 2 and i > 0)
    isOk = true;

if (not isOk) {
    printf("OK");
}

替代關鍵詞有哪些?

  能夠在iso646.h頭文件中找到:微信

#define and    &&
#define and_eq &=
#define bitand &
#define bitor  |
#define compl  ~
#define not    !
#define not_eq !=
#define or     ||
#define or_eq  |=
#define xor    ^
#define xor_eq ^=

關於替代關鍵詞

  • 使用andor這些關鍵詞時能夠避免只寫一個&|致使邏輯錯誤。
if (x && y) { ... }

/* 遺留了&可能致使程序意想不到的缺陷 */
if (x & y) { ... }

/* 而遺留了and則直接致使編譯錯誤,從而發現錯誤 */
if (x and y) { ... }
  • 可讀性更好,與閱讀大量單詞相比,閱讀符號並瞭解它們的含義理解起來要快得多。
  • 在好久之前的計算機鍵盤中因爲沒有& | ^ 等字符,須要使用關鍵詞來標識。
  • 不一樣的編譯器對這些關鍵詞可能不支持。Qt君使用mingw7.3.0編譯器能夠經過,而使用MSVC2017則編譯不經過,須要設置編譯器選項/Za以支持替代關鍵字。
  • 彷佛符號表達的方式在使用上更加流行。

更多精彩文章請關注微信公衆號:「Qt君」code

相關文章
相關標籤/搜索