Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!cmcl2!husc6!panda!genrad!decvax!tektronix!teklds!dadla!tekla!dant From: dant@tekla.UUCP (Dan Tilque) Newsgroups: net.lang.c Subject: Re: for != while Message-ID: <749@tekla.UUCP> Date: Fri, 5-Sep-86 16:44:41 EDT Article-I.D.: tekla.749 Posted: Fri Sep 5 16:44:41 1986 Date-Received: Sun, 7-Sep-86 05:56:42 EDT Organization: Tektronix, Inc., Beaverton, OR Lines: 63 From: mikeb@copper.UUCP (Mike Beckerman) >In article <15525@ucbvax.BERKELEY.EDU> ballou@brahms.UUCP (Kenneth R. Ballou) writes: >>In article <86900030@haddock> karl@haddock writes: >>> >>>It's well known that the equivalence between for and while breaks down if >>>there's a "continue" statement. Here's another case I just discovered: >>> >>>main() { >>> char *foo = "outer"; >>> for (;; printf(foo),exit(0)) { >>> char *foo = "inner"; >>> } >>>} >>> >>>This prints "outer" (vax SVR2 compiler), though the for-while equivalence >>>might lead one to expect "inner". >> >>I don't think the issue here is equivalence of for and while statements. >>The point is that the scope of the inner 'foo' is the compound statement >>which is the body of the for statement. So, quite rightly, the 'foo' >>given as the argument to printf in the third expression of the for statement >>refers to the most closely nested declaration of 'foo' -- the body of the >>for statement is one block level higher and is not visible at this point. > >That was my first thought as well, but both K&R and the proposed ANSI C standard >define the "for" loop as follows: > > for (expression-1 ; expression-2 ; expression-3) statement > > is equivalent to > > expression-1; > while (expression-2) { > statement > expression-3; > } > >which to me says that the example should have printed "inner". > Ken Ballou is correct, and the equivalence above is correct. The equivalence of the first example is this: main() { char *foo = "outer"; while () { { char *foo = "inner"; } printf(foo),exit(0)); } } The *foo = "inner" applies only within the inner braces (which delineate the statement). The printf(foo) goes outside those braces. Dan Tilque UUCP: tektronix!dadla!dant CSnet: dant%dadla@tektronix ARPAnet: dant%dadla%tektronix@csnet-relay Mass extinction; it's not just for dinosaurs anymore.