为什么此代码会产生引用逗号运算符的警告?

发布于 2024-10-31 23:51:38 字数 771 浏览 1 评论 0原文

在回答这个问题时,我遇到了这段代码......

#include <iostream>

int main()
{
    int const income = 0;
    std::cout << "I'm sorry your income is: " < income;    // this is line 6
}

其中包含错字。第 6 行的第二个(预期的)<< 运算符被意外地写为 <

除此之外,使用 GCC 4.3.4 或 4.4.3 编译代码会导致警告:

prog.cpp: In function ‘int main()’:
prog.cpp:6: warning: right-hand operand of comma has no effect

我的问题:为什么是否产生了该特定警告?它指的是哪个逗号运算符?

注意:我并不是提倡在 cout 语句中故意使用单个 < 我只是在试图找出答案时偶然发现了这个警告我链接到的另一个问题的答案,我很好奇编译器为什么会生成它。

When answering this question, I came across this code...

#include <iostream>

int main()
{
    int const income = 0;
    std::cout << "I'm sorry your income is: " < income;    // this is line 6
}

...which contains a typo. The second (intended) << operator on line 6 has been accidentally written as a <.

That aside, compiling the code using GCC 4.3.4 or 4.4.3 results in a warning:

prog.cpp: In function ‘int main()’:
prog.cpp:6: warning: right-hand operand of comma has no effect

My question: why is that particular warning produced? Which comma operator is it referring to?

NOTE: I'm not advocating deliberately using a single < in a cout statement. I merely stumbled across this warning while trying to figure out an answer to the other question I've linked to, and am curious as to why the compiler generates it.

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

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

发布评论

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

评论(2

淡墨 2024-11-07 23:51:38

我认为他们只是忘记更改警告文本

int main() {
   1, 2;
}

prog.cpp:2: warning: left-hand operand of comma has no effect
prog.cpp:2: warning: right-hand operand of comma has no effect

expr, expr 运算符计算左操作数,然后计算右操作数并产生右操作数的计算结果。如果正确的操作数没有效果并且其值未被使用,则可能是程序中的错误。

现在看来,他们只是滥用了上述警告文本来警告其他二元运算符。

I think they just forgot to change the warning text

int main() {
   1, 2;
}

prog.cpp:2: warning: left-hand operand of comma has no effect
prog.cpp:2: warning: right-hand operand of comma has no effect

The expr, expr operator evaluates the left operand, then evaluates the right operand and yields the result of the right operand's evaluation. If the right operand has no effect and its value is not used, it's probably a bug in the program.

Now they just abused the above warning text to warn for other binary operators, it seems.

烟火散人牵绊 2024-11-07 23:51:38

您给定的程序不会使用 MSVC2010 为我生成该警告,它只会生成

警告 C4552:“<” : 运算符没有作用;具有副作用的预期运算符

因为这应该是 venue; 之前的 <<
(注意:Ideone 根本不会产生警告。)

Your given program doesn't produce that warning for me with MSVC2010, it only produces

warning C4552: '<' : operator has no effect; expected operator with side-effect

As that should be a << before income;.
(Note: Ideone doesn't produce a warning at all.)

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