9
#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    ifstream file0( "file0.txt" );
    ifstream file1( "file1.txt" );

    if (file0 != file1) {
        cout << "What is being compared?" << endl;
    }

} 

If the above code, what is being compared in the conditional? I believe it is pointer values but I am unable to find supporting evidence.

Thanks!

rshepherd
  • 1,396
  • 3
  • 12
  • 21
  • A step towards "the pointers are being compared" can be taken by testing for equality. Should not cout. – Tom Nov 27 '10 at 22:53

1 Answers1

4

When doing a comparison on an ifstream the operator void* will be called. If you are using visual studio you can see this if you choose to see the disassembly of the code.

The operator can be found here. As you can see mentioned:

The pointer returned is not intended to be referenced, it just indicates success when none of the error flags are set.

So if both ifstreams fail, they will be equal. If they succeed (although I am not sure where the pointer value comes from) they will not be equal [this has been tested on VS].

Community
  • 1
  • 1
default
  • 11,485
  • 9
  • 66
  • 102
  • 1
    Say, how does the compiler know to choose operator void*() over operator bool()? What defines the precedence? – chrisaycock Nov 27 '10 at 23:27
  • @chris: I was actually thinking about the same thing. That is beyond my knowledge though.. – default Nov 27 '10 at 23:30
  • 2
    Streams don't have an `operator bool`. The returned `void*` is implicitly convertible to bool in boolean contexts (`if (std::cin)...`). – UncleBens Nov 28 '10 at 13:44
  • 2
    @UncleBens Since C++11, streams have `operator bool`. However no ambiguity for compiler because `operator bool` is `explicit`. e.g. developer has to request `bool` value to use `operator bool`. For instance: `if ((bool)file0)` – oHo Nov 02 '12 at 10:16