或无效 C++ : 为什么这段代码可以编译?

发布于 2024-08-05 02:47:25 字数 403 浏览 3 评论 0原文

这是我用 QtCreator 制作的一个非常简单的 C++ 应用程序:

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

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

对我来说,这不是有效的 C++,因为关键字 or 不是保留关键字。

但如果我编译并运行它,它工作正常,没有任何警告!退出代码为 0,如果我更改 b = 4,则退出代码为 1!

我没有包含任何内容来确保没有隐藏的定义。

这对我来说真的很奇怪。这是 Qt 定义的东西吗?我在文档中没有找到任何与此相关的内容。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

金兰素衣 2024-08-12 02:47:25

根据 维基百科

C++ 定义关键字作为别名
对于许多功能的符号
作为运算符:and (&)、bitand (&)、
and_eq (&=)、or (||)、bitor (|)、or_eq
(|=)、异或 (^)、xor_eq (^=)、非 (!)、
not_eq (!=), compl (~)。

正如 MadKeithV 指出 ,这些替换来自 C 的 iso646.h,并作为运算符关键字包含在 ISO C++ 中。 iso646.h 的维基百科文章表示,这些关键字的原因确实是针对国际键盘和其他非 QWERTY 键盘,这些键盘可能无法轻松访问这些符号。

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.

国际总奸 2024-08-12 02:47:25

or 是一个 C++ 关键字,您可以使用它来代替 ||。没有魔法。

对于 and 以及大多数其他逻辑运算符也是如此。不过,通常最好坚持使用众所周知的名称,以避免这样的混淆。如果您使用 ,有人会想知道“为什么会编译”;)

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" ;)

痴意少年 2024-08-12 02:47:25

iso646.h 定义了许多运算符替代方案 - 它是 C++ 标准的一部分。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文