A question of style
Jim Vlcek
vlcek at mit-caf.MIT.EDU
Sat Dec 2 10:22:12 AEST 1989
In article <427 at jhereg.Minnetech.MN.ORG> mark at jhereg.minnetech.mn.org (Mark H. Colburn) writes:
>In article <1989Nov30.001947.14883 at aqdata.uucp> sullivan at aqdata.uucp (Michael T. Sullivan) writes:
Michael Sullivan (in the aqdata reference), proposes a 'proper' use of
the comma operator:
while (c = getchar(), c != EOF)
{
...
}
To which Mark Colburn replies:
The code above could be written as
while (c = getchar && c != EOF) {
...
}
Which most programmers would find "more intuitive" than the comma
separated one.
Sorry, but most programmers would find it "wrong". In fact, I think
most programmers would find it difficult to get the thing _more_ wrong
than this. First, you need the parenthesis after getchar (getchar())
- that omission, however, may be a lucky one in that it would keep
this mess from even compiling. Second, the value assigned to ``c''
will not be the desired value (the value returned by getchar()), but
instead will be the value of the expression
getchar() && c != EOF
This, of course, screws up the comparison with EOF, which ``c'' can
never equal (unless it was so initialized) as the && operator returns
only the values 0 and 1. That comparison is also made with the value
of ``c'' from the last iteration of the loop, as the assignment
to ``c'' takes place _after_ the comparison to EOF. Even if you
corrected all these problems by writing
while ((c = getchar()) && c != EOF) {
}
the semantics would still be changed in that the loop would terminate
on a return from getchar() of either 0 or EOF, whereas the previous
example terminates only on EOF (Barry Margolin already pointed this
out).
What you wanted, of course, was
while ((c = getchar()) != EOF) {
}
which, I am fairly confident, is given (probably verbatim) in K&R1.
Sorry if I seem pedantic, but I was amazed at how wrong this thing
was. Even as I was writing this posting, I kept finding more things
wrong with it - I may have even missed a few.
Of course, if I'm wrong, this posting was done by an imposter, not Jim
Vlcek.
Fuck the moon; let's get | Jim Vlcek (vlcek at caf.mit.edu)
the Earth straightened out. | (vlcek at athena.mit.edu)
More information about the Comp.lang.c
mailing list