I'm a grader and a little confused. One of my students placed an ifstream object in their if statement.
1 2 3 4
ifstream reader(filename, ifstream::in);
if (reader) {
// Read stuff
}
Is this actually valid? Will "reader" ever return false? I've always thought the only things that can be used inside if statements are booleans, integers, or other primitive data types (but not constructed classes).
Did the student make a mistake or is this something I didn't know?
Yes, this is valid because all C++ streams implement operatorbool() and thus can be implicitly converted to a boolean. In fact, I often recommend that the correct way to read or write a file is like this:
1 2 3 4 5 6 7 8
if(std::ifstream in {"file.txt"})
{
//code here
}
else
{
std::cerr << "Error opening file.txt" << std::endl;
}
This prevents the file stream from being used elsewhere and it ensures that it gets closed at the end of the if-else (it uses RAII).