Difference between “&&” and “and” operators [duplicate]

旧城冷巷雨未停 提交于 2019-11-30 17:46:00

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

There is none1. The "alternative" aspect of these operators means that they can be used to construct the exact same expressions from a semantic perspective.

Where and when do I use and over &&?

This is largely a matter of preference. I'm too used to && to not use it, but can understand if someone finds and more readable.

why does C++ introduce alternative operators?

C++ was designed to be available on a variety of character sets and platforms. Trigraphs, like Bathsheba pointed out, are another example of such a feature. If a character set would not allow && to be written (say, because it simply didn't have the & character) then one can still get by with the alternative representation. Nowadays, it's largely moot.


1 Actually, upon further thinking, my answer to your first question can be refined. There is a slight lack of equivalence, pertaining to how tokens are parsed. && doesn't require a space to be parsed as a separate token, while and does. That means:

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

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

and, or, not, &c. are examples of the alternative operators.

For the full list see http://en.cppreference.com/w/cpp/language/operator_alternative; the opening paragraph is a raison d'etre:

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.

If I were you I'd shy away from using them, much in the same way as you ought to shy away from using digraphs and trigraphs, even if the latter make for interview fun.

Trigraphs for example are explicitly discontinued from C++17. You might see and &c. being dropped in future standards too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!