关于C++代码`return cout<<"NO"<<endl,0;`的若干技术疑问
Hey there! Let's unpack this line of code and answer all your questions clearly:
return cout<<"NO"<<endl,0; 1. Does cout << have a return value?
Absolutely! The << insertion operator for std::cout returns a reference to the cout object itself. That's exactly why you can chain multiple << calls together (like cout << "Hi" << " there!" << endl) — each << hands back the cout object, so the next << can keep writing to it.
2. Is this code returning one of two values?
Nope, it only returns a single value: 0. The comma here is the comma operator, a quirky C++ operator that works like this:
- First, it runs the expression on the left (
cout<<"NO"<<endl) — this prints "NO" and a newline, but we don't care about its result. - Then, it evaluates the expression on the right (
0) and uses that as the final result of the entire comma expression.
So this one-liner is totally equivalent to writing:
cout << "NO" << endl; return 0;
It's just a compact (some might argue overly terse) way to combine a print and a return into one line.
3. How does the program decide which value to return?
The comma operator enforces strict left-to-right order. The left expression is executed first, but its result is discarded entirely. Only the value of the right-hand expression gets passed to the return statement. So in this case, the program will always return 0 — after printing "NO" to the console, of course.
内容的提问来源于stack exchange,提问作者glennmark

