问题
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.
回答1:
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.
回答2:
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.)
来源:https://stackoverflow.com/questions/5665611/why-does-this-code-produce-a-warning-referring-to-the-comma-operator