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.
Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3” becomes equivalent to “ (a = 1), 2, 3”. That is why we get output as 1 in the second program.
Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3” becomes equivalent to “ (a = 1), 2, 3”. That is why we get output as 1 in the second program.
In C++, we can overload the comma operator using Operator Overloading. For Example: For “ Send the query X to the server Y and put the result in variable Z”, the “and” plays the role of the comma. The comma operator (, ) is used to isolate two or more expressions that are included where only one expression is expected.
So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3” becomes equivalent to “ (a = 1), 2, 3”. That is why we get output as 1 in the second program.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With