我在浏览 cppreference 时看到了 alternative operators(如 and
、or
、not
等)。
它们是 &&
、 ||
、 !
等“普通”运算符的替代品。
我检查了使用 &&
和 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++ 为什么要引入替代运算符(如
and
、or
、not
等)?
最佳答案
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/