为什么这段代码会产生一个指向逗号操作符的警告?

Why does this code produce a warning referring to the comma operator?

本文关键字:操作符 警告 一个 段代码 代码 为什么      更新时间:2023-10-16

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

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

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

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操作符先对左操作数求值,然后对右操作数求值,最后得到右操作数的求值结果。如果右操作数没有作用,并且没有使用它的值,则可能是程序中存在错误。

现在他们似乎滥用了上面的警告文本来警告其他二进制操作符。

你给定的程序不会用MSVC2010为我产生警告,它只产生

警告C4552: '<':操作符无效;预期的有副作用的操作符

应该是<<income;之前。(注意:Ideone根本不产生警告。)