Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...