0

The "DumpFile.ino" example sketch from the SD library tries to open a file off an SD card, read its contents, and write them to the Serial Monitor. I am confused in how the following if() statement is evaluated:

File dataFile = SD.open("datalog.txt");

if (dataFile) {
// read and print, then close
}
else {
// print error message
}

There must be some implicit conversion on dataFile which depends on whether or not SD.open("myFile.txt") was successful. I would like to understand how this implicit conversion occurs. Which property of the File object determines if the if() statement evaulates true or false?

1
  • 1
    It calls the bool() operator.
    – Majenko
    Aug 16 '16 at 22:33
1

There is an operator bool which does the test:

File::operator bool() {
  if (_file) 
    return  _file->isOpen();
  return false;
}

When used inside an if the compiler invokes the operator bool() which does the test you see above.

1
  • Thanks, it is obvious now that I see it. I've indeed found that this defined in the File implementation.
    – j0ntan
    Aug 16 '16 at 22:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.