Search code examples
c++language-lawyerifstream

Typo: bool to int conversion induced error in std::ifstream under Linux


I had a typo (|| instead of |) and noticed such a code fails with GCC and compiles with Visual. I know that the second parameter of std::ifstream is an int. So theoretically, a bool has to be converted implicitely to an int. So why it fails?

Example inducing the error (I just used some ints instead of the flags).

#include <fstream>

int main(int argc, char * argv[]) {
  std::ifstream("foo", 2 | 3 || 4)
}

Solution

  • std::ifstream's constructor takes as second argument an std::ios_base::openmode which is typedefed from an implementation defined type:

    typedef /*implementation defined*/ openmode;
    

    It seems Visual uses integers, GCC does not, and it's why your code fails on GCC.