Search code examples
c++referenceistream

Returning a reference to istream in C++


I read this on Accelerated C++. Here is a simplified version.

istream& read_hw(istream& in, Student_info& s)
{    
    in >> s.name >> s.midterm >> s.final;
    return in;
}

Then, we can call the function as:

Student_info s;
read_hw(cin, s);

My question is,

  1. What's the point of returning the reference to istream? Since both the two parameters are passed by reference;
  2. While calling the function, we don't seem to care about the returning value

Solution

  • You should read the next paragraph:

    Returning the stream allows our caller to write

    if (read_hw(cin, homework)){/*...*/} 
    

    as an abbreviation for

    read_hw(cin, homework);
    if (cin) {/*...*/}