为什么此代码会产生引用逗号运算符的警告?
在回答这个问题时,我遇到了这段代码......
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为他们只是忘记更改警告文本
expr, expr
运算符计算左操作数,然后计算右操作数并产生右操作数的计算结果。如果正确的操作数没有效果并且其值未被使用,则可能是程序中的错误。现在看来,他们只是滥用了上述警告文本来警告其他二元运算符。
I think they just forgot to change the warning text
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.
您给定的程序不会使用 MSVC2010 为我生成该警告,它只会生成
因为这应该是
venue;
之前的<<
。(注意:Ideone 根本不会产生警告。)
Your given program doesn't produce that warning for me with MSVC2010, it only produces
As that should be a
<<
beforeincome;
.(Note: Ideone doesn't produce a warning at all.)