or is not valid C++ : why does this code compile?

与世无争的帅哥 提交于 2019-12-17 11:29:07

问题


Here is a very simple C++ application I made with QtCreator :

int main(int argc, char *argv[])
{
    int a = 1;
    int b = 2;

    if (a < 1 or b > 3)
    {
       return 1;
    }
    return 0;
}

To me, this is not valid C++, as the keyword or is not a reserved keyword.

But if I compile and run it, it works fine without any warnings ! The exit code is 0 and if I change b = 4, the exit code is 1 !

I'm not including anything to make sure there is no hidden define.

This is really strange to me. Is this something Qt is defining ? I didn't find anything in the documentation regarding that.


回答1:


According to Wikipedia:

C++ defines keywords to act as aliases for a number of symbols that function as operators: and (&&), bitand (&), and_eq (&=), or (||), bitor (|), or_eq (|=), xor (^), xor_eq (^=), not (!), not_eq (!=), compl (~).

As MadKeithV points out, these replacements came from C's iso646.h, and were included in ISO C++ as operator keywords. The Wikipedia article for iso646.h says that the reason for these keywords was indeed for international and other non-QWERTY keyboards that might not have had easy access to the symbols.




回答2:


or is a C++ keyword, and you're allowed to use it instead of ||. There is no magic.

The same goes for and and most other logical operators. It's generally best to stick to the commonly known names though, to avoid confusion like this. If you use or, someone will wonder "why does this compile" ;)




回答3:


iso646.h defines a number of operator alternatives - it's part of the C++ standard.



来源:https://stackoverflow.com/questions/1433345/or-is-not-valid-c-why-does-this-code-compile

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