Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c Subject: Re: use of if (!cptr) and if (cptr) && a programming error Message-ID: <9720@alice.UUCP> Date: 1 Aug 89 20:08:51 GMT References: <10099@mpx2.mpx.com> <93@microsoft.UUCP> <10100@mpx2.mpx.com> <10592@riks.csl.sony.JUNET> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 31 In article <10592@riks.csl.sony.JUNET>, diamond@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@europa.att.com