Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 228
Rui Liu Avatar asked Dec 21 '25 11:12

Rui Liu


1 Answers

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) {/*...*/}
like image 132
cnicutar Avatar answered Dec 23 '25 02:12

cnicutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!