use of if (!cptr) and if (cptr) && a programming error
Andrew Koenig
ark at alice.UUCP
Wed Aug 2 06:08:51 AEST 1989
In article <10592 at riks.csl.sony.JUNET>, diamond at csl.sony.JUNET (Norman Diamond) writes:
> But! What about the following famous idiom!
> int ch; /* everyone knows it cannot be char */
> while ((ch = getchar()) != EOF) { ... }
> The old value of ch might be compared to EOF? The loop might be
> executed in incorrect cases (and might not be executed sometimes when
> it should be)?
> IS THIS REALLY TRUE ??????????????????
> Are there really millions of broken C programs due to this idiom?
No, this works fine.
The reason it works is that both operands of an operator
must be completely evaluated before the operator itself is
[unless the operator is && or || or ?:]. Thus, before
the comparison is done, the two subexpressions
ch = getchar()
and
EOF
must be evaluated. There is no guarantee of which one is evaluated
first, but you can't compare two values until you know what they are.
--
--Andrew Koenig
ark at europa.att.com
More information about the Comp.lang.c
mailing list