-7

What's the return value (not printed) of

cout << 1, 2, 3, 4, 5;

How can I debug this code?

I need explain how work ostream and cout also.

Dmitry
  • 109
  • 8
  • 2
    Why do you expect the comma operator to work differently with `std::cout` than it normally does? And what have you tried doing? – UnholySheep Apr 25 '18 at 15:59
  • 1
    What happened when you tried to run it? What did you expect and why'd you expect it? – scohe001 Apr 25 '18 at 16:00
  • 2
    Review http://en.cppreference.com/w/cpp/language/operator_precedence and then add brackets. – Richard Critten Apr 25 '18 at 16:01
  • 1
    Possible duplicate of [How does the Comma Operator work](https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) –  Apr 25 '18 at 16:05

1 Answers1

0

The return value is an int with the value 5. As side effect, 1 will be printed.

#include <iostream>

using namespace std;

int main(void)
{
    auto rv = (cout << 1, 2, 3, 4, 5);

    std::cout << rv;

    return 0;
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 2
    `(cout << 1), 2, 3, 4, 5` – Richard Critten Apr 25 '18 at 16:02
  • Depends. If you parenthesize as `(cout << 1, 2, 3, 4, 5)` you get `5`. If you don't add parentheses but assign to a variable like `auto r = cout << 1, 2, 3, 4, 5` the `=` operator binds stronger than `,` and you get `std::ostream&` as type for `r`. – Niklas R Apr 25 '18 at 16:07
  • @NiklasR I tried that first, but it would actually not compile for me, `std::basic_ostream> &std::basic_ostream>::operator =(const std::basic_ostream> &)': attempting to reference a deleted function` – nvoigt Apr 25 '18 at 16:13
  • @nvoigt that is because declaring a variable as `auto` doesn't deduce a reference, so the type of `r` will actually be `std::ostream` even though the value being assigned is a `std::ostream&`. A `std::ostream` can't be copied, hence the "deleted function" error. Declaring `r` as `auto&` would make it a `std::ostream&` reference. – Remy Lebeau Apr 25 '18 at 17:33
  • @RemyLebeau Did you try? Because I get the same error setting it explicitely to an `ostream&` and I still get it even when I split declaration and assignment. – nvoigt Apr 25 '18 at 17:38