On Jan 12, 4:46 am, Jerry Coffin <jcof...@taeus. comwrote:
In article <OQwhj.42$QA... @newsfe06.lga>, tazmas...@rocke tmail.com
says...
[ ... ]
I do ( var = something ) == something
all the time, and have always considered it clean.
I don't see much reason to do it in the case of the code
earlier in this thread, but in some cases, I think this is
exactly the correct thing to do.
Just for one example, I believe when writing code to open a
file using fopen, the correct way to do it is something like:
if (NULL==(file=fo pen(whatever, "r")))
// handle error
Getting into the habit of coding this way assures that a
problem with opening the file will always be handled. Code
that separates opening and testing:
file = fopen(whatever, "r");
if ( file == NULL)
// handle error
...makes some types of errors much easier. One is leaving out
the testing code entirely. The other is accidentally inserting
something between opening and testing that depends on the file
having been opened correctly. Both are obviously errors, but
are also easy to miss until the code is tested with a file
that can't be opened.
I've not found this to be a problem, and do generally do the
open separately. Especially with [io]fstream:
std::ifstream input( filename.c_str( ) ) ;
if ( ! input.is_open() ) ...
If there is an exception to my rule, however, it is when the
return value contains an error indicator---especially, if it is
only an error indicator---and the function has serious side
effects otherwise. Personally, I don't nest the assignment if
the return value is saved, but I don't have too much problem
with people who write things like:
while ( (length = read( fd, buffer, bufSize )) 0 ) {
}
, and of course, I do write things like:
while ( std::getline( input, line ) ) {
}
which is really fairly similar, except that the additional state
is saved in the iostream object (i.e. failbit, eofbit, etc.),
and not in a variable that I explicitly assign. Ideally, one
would like for a condition never to have any side effects, but
sometimes, the cure is worse than the disease (although the only
problem I have with something like:
std::getline( input, line ) ;
while ( input ) {
//...
std::getline( input, line ) ;
}
is that it isn't idiomatic. Independantly of any other
advantages or disadvantages, an experienced C++ programmer who
sees it will ask himself why the idiomatic form wasn't used.
--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34