8

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

#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声明中故意使用单个。 我只是在试图找出我链接到的另一个问题的答案时偶然发现了这个警告,并且很好奇编译器为什么会生成它。

4

2 回答 2

7

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

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左操作数,然后计算右操作数并产生右操作数的计算结果。如果正确的操作数没有作用并且它的值没有被使用,它可能是程序中的一个错误。

现在他们似乎只是滥用上述警告文本来警告其他二进制运算符。

于 2011-04-14T15:30:22.233 回答
1

您给定的程序不会使用 MSVC2010 对我产生警告,它只会产生

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

因为那应该是<<before income;。(注意:Ideone根本不会产生警告。)

于 2011-04-14T15:29:48.333 回答