J
James Kanze
* Thomas J. Gritzan:
He must really like the loop and a half idiom, to use it when
there isn't a half a loop to begin with.
Actually, in this case, the code is just wrong. The test really
should be:
if ( ¡ infile ) break ;
If the file doesn't end with a '\n', then his code will not "Do
something with value" for the last value. (Of course, if a file
does not end with a '\n', it's not a legal text file. But most
of us would like to be a bit more tolerant, on systems which
allow it.)
As a general rule, any time you see something other than what is
in the FAQ, you can probably assume that the person who wrote it
isn't familiar with iostreams.
The example in the FAQ is not as ugly as this code.
The FAQ code,
int i = 0;
while (std::cin >> x) { // RIGHT! (reliable)
++i;
// Work with x ...
}
is apparently simpler and shorter, because it uses implicit
conversion, it uses a side-effect based expression, it leaves
out a declaration, it exposes local variable to outside code,
and it doesn't check for errors.
It's more than apparently simpler, but...
The most important reason to use it is because it is the
standard idiom. I don't particularly like the side effects in a
condition either, but in this case, the idiom is so ubiquious as
to cause questions to be raised when it isn't used. If it
weren't for this, I'd write:
int i ;
std::cin >> i ;
while ( std::cin ) {
// ...
std::cin >> i ;
}
. You might prefer:
for (; {
int i ;
std::cin >> i ;
if ( ! std::cin ) {
break ;
}
// ...
}
(even if in this case, it's a bit longer.) But that's not the
issue here. I don't write it like that, however, because as I
said above---any time you see something other than what is in
the FAQ... Most experienced programmers, on seeing such code,
would start by asking if I understood iostream, or if he knew
better, by asking what was special here that caused me to break
with the standard idiom.
Judging from discussions here and elsewhere, few programmers
understand what that code /actually does/ -- and doesn't do.
Judging from discussions here and elsewhere, few programmers
know iostream very well at all. (Not that that stops them from
criticising it.)
To check own understanding, what does (std::cin >> x) as
condition, actually check?
failbit and badbit. The only two bits which are relevant with
regards to the success of an operation.
A more important question is what actually might cause it to be
false. And in a lot of cases, how can you distinguish what the
real reason was, and respond accordingly. And while, unlike
you, I rather like iostream, I'll have to admit that error
reporting is not its strong point; I can construct cases where
you cannot correctly determine the real reason.