在回答this question时,我遇到了这段代码......
#include <iostream>
int main()
{
int const income = 0;
std::cout << "I'm sorry your income is: " < income; // this is line 6
}
...其中包含拼写错误。第6行的第二个(预期)<<
运算符被意外写为<
。
除此之外,编译代码using 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
。我只是偶然发现了这个警告,同时试图找出答案。我已经链接到的其他问题,并且很好奇编译器为什么会生成它。
答案 0 :(得分:6)
我认为他们只是忘了更改警告文字
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
运算符计算左操作数,然后计算右操作数并产生右操作数评估的结果。如果右操作数没有效果且未使用其值,则可能是程序中的错误。
现在他们只是滥用上述警告文本来警告其他二元运算符。
答案 1 :(得分:1)
您的给定程序不会为我生成MSVC2010的警告,它只生成
警告C4552:'&lt;' :运算符无效;具有副作用的预期算子
因为在<<
之前应该是income;
。
(注意:Ideone根本不会产生警告。)