"&&" 和 "and" 运算符的区别

Difference between "&&" and "and" operators

我在浏览cppreference时看到了alternative operators(如andornot等)。

它们是 "normal" 运算符的替代品,例如 &&||!

我检查了使用 &&and 的程序集。两个版本生成相同的程序集。

代码:

#include <iostream> 

int n = 1;
int main()
{
// if(n > 0 && n < 5)
   if(n > 0 and n < 5)
   {
       std::cout << "n is small and positive\n";
   }
}

所以我的问题是:

What is the difference between the && and and operators?

有none1。这些运算符的 "alternative" 方面意味着它们可用于从语义角度构建完全相同的表达式。

Where and when do I use and over &&?

这主要是个人喜好问题。我太习惯了 && 不使用它,但如果有人发现 and 更具可读性,我可以理解。

why does C++ introduce alternative operators?

C++ 被设计为可用于各种字符集和平台。正如 Bathsheba 所指出的那样,Trigraphs 是这种特征的另一个例子。如果字符集不允许写入 &&(比如,因为它根本没有 & 字符),那么仍然可以使用替代表示法。如今,它基本上没有实际意义。


1 其实我对你第一个问题的回答,再细想一下,还可以细化一下。关于令牌的解析方式,略微缺乏等效性。 && 不需要将 space 解析为单独的标记,而 and 需要。这意味着:

void foo(bool b1, bool b2) {
  if(b1&&b2) { // Well formed
  }

  if(b1andb2) { // ill formed, needs spaces around `and`
 }
}

andornot、等等。是 替代运算符的示例

完整列表见http://en.cppreference.com/w/cpp/language/operator_alternative;开头一段是 存在的理由:

C++ (and C) source code may be written in any non-ASCII 7-bit character set that includes the ISO 646:1983 invariant character set. However, several C++ operators and punctuators require characters that are outside of the ISO 646 codeset: {, }, [, ], #, \, ^, |, ~. To be able to use character encodings where some or all of these symbols do not exist (such as the German DIN 66003), C++ defines the following alternatives composed of ISO 646 compatible characters.

如果我是你,我会避免使用它们,就像你应该避免使用二字母和三字母一样,即使后者会让面试变得有趣。

例如,Trigraph 已明确从 C++17 中停用。您可能会看到 and &c。在未来的标准中也会被删除。