c++ - "&&"和 "and"运算符之间的区别

标签 c++ logical-operators

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

它们是 &&||! 等“普通”运算符的替代品。

我检查了使用 &&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";
   }
}

所以我的问题是:

  • &&and 运算符有什么区别?
  • 我应该在何时何地使用 and 而不是 &&
  • 如果没有区别,那么 C++ 为什么要引入替代运算符(如 andornot 等)?

最佳答案

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

没有1。这些运算符的“替代”方面意味着它们可用于从语义角度构建完全相同的表达式。

Where and when do I use and over &&?

这在很大程度上是一个偏好问题。我太习惯了 && 不使用它,但可以理解是否有人发现 and 更具可读性。

why does C++ introduce alternative operators?

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


<子> 1 其实,经过进一步思考,我对您第一个问题的回答是可以细化的。关于如何解析 token ,稍微缺乏等价性。 && 不需要将空格作为单独的标记进行解析,而 and 则需要。这意味着:

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

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

关于c++ - "&&"和 "and"运算符之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47174920/

相关文章:

c++ - 因使用双重逻辑非 (!!) 运算符而感到困惑

c - 如何使用C在bash中实现逻辑运算符?

c - for 循环中的多个测试条件在逻辑上与 && 相关联

C++ 在 'std::cin' 中不匹配 'operator>>'

c++ - 方法指针的静态数组

c++ - 错误消息 : "Assertion ' t = find_next_time_event( m )' failed at pulse/mainloop.c" ? ...(C++)

c++ - 通过引用另一个类方法传递 vector 成员变量

c++ - CEdit edit_box hwnd null

c++ - 非(~)与否定(!)

c - 为什么当 "k"计算结果为 true 时,语句 "m =++i &&++j ||++k"中的 "++i&&++j"不增加?