Reputation: 385274
In GCC 4.7.0 20111217, GCC 4.1.2, GCC 4.3.4 and GCC 4.5.1:
#include <iostream>
#include <fstream>
int main() {
std::ifstream f;
std::cout << f.get() << ", " << f.good() << ", " << f.bad();
}
// Output: -1, 1, 0
I'd have expected -1, 0, 1
(which Clang 3.1 gives me), because of these paragraphs:
[C++11: 27.7.2.3]:
int_type get();
4 Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts a character
c
, if one is available. Otherwise, the function callssetstate(failbit)
, which may throwios_base::failure
(27.5.5.4),
5 Returns:c
if available, otherwisetraits::eof()
.
and:
[C++11: 27.9.1.1/3]:
In particular:
- If the file is not open for reading the input sequence cannot be read.
- If the file is not open for writing the output sequence cannot be written.
- A joint file position is maintained for both the input sequence and the output sequence.
Is GCC in the wrong here? Did an implementer misinterpret the "otherwise" in [C++11: 27.7.2.3/4]
? Or did I misinterpret the standard?
Upvotes: 3
Views: 249
Reputation: 21123
The problem is that the order that the operations on f is called is not specified by the standard. The compiler is free to call f.good()
, f.bad()
, and f.get()
in any order it chooses.
Try changing to print it on separate lines.
Upvotes: 2
Reputation: 385274
I've just realised I'm being silly:
#include <iostream>
#include <fstream>
int main() {
std::ifstream f;
std::cout << f.get() << ", ";
std::cout << f.good() << ", " << f.bad();
}
// Output: -1, 0, 0
Unspecified evaluation order. Duh.
Upvotes: 1