开发者

When did "and" become an operator in C++

I have some code that looks like:

static const std::string and(" AND ");

This causes an error in g++ like so:

Row.cpp:140: error: expected unqualified-id before '&&' token

so after cursing the fool that defined "and" as &&, I added

#ifdef and
#undef and
#endif

and now I get

Row.cpp:9:8: error: "and" cannot be used as a macro name as it is an operator in C++

Which leads to my question of WHEN did "and"开发者_开发问答 become an operator in C++? I can't find anything that indicates it is, except of course this message from g++


From the C++03 standard, section 2.5:

2.5 Alternative tokens

Alternative token representations are provided for some operators and punctuators. In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2.

Table 2—alternative tokens

alternative primary 
  <%         { 
  %>         } 
  <:         [ 
  :>         ] 
  %:         # 
  %:%:       ## 
  and        && 
  bitor      | 
  or         || 
  xor        ˆ 
  compl      ˜ 
  bitand     & 
  and_eq     &= 
  or_eq      |= 
  xor_eq     ˆ= 
  not        ! 
  not_eq     != 


They've been there since C++ 98. They're listed in the §2.5/2 of the standard (either the 1998 or the 2003 edition). The alternate tokens include: and, or, xor, not, bitand, bitor, compl, and_eq, or_eq, xor_eq, not, not_eq.


You can use -fno-operator-names to disable this. Alternatively, you can name your std::string object something else!


There are several such alternatives defined in C++. You can probably use switches to turn these on/off.


According to C++ Standard 2.12 there are predefined preprocessor tokens "which are used in the syntax of the preprocessor or are converted into tokens for operators and punctuators." and is one of them. In new C++ Standard there is new 2.12/2:

Furthermore, the alternative representations shown in Table 4 for certain operators and punctuators (2.6) are reserved and shall not be used otherwise:

and and_eq bitand bitor compl not
not_eq or or_eq xor xor_eq


They were added because some of those characters are difficult to type on some keyboards.


I don't know when it was introduced, it may well have been there from the beginning, but I believe the reason it's there is as an alternative to && for people with restricted character sets i.e. where they don't actually have the ampersand character.

There are many others too eg. and_eq, or, compl and not to name just a selection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜