franka@mmintl.UUCP (Frank Adams) (09/09/86)
In article <749@tekla.UUCP> in net.lang.c dant@tekla.UUCP 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". >the ... above is correct. The >equivalence of the ... 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. This is fine as far as C goes. In C++, one may instead write main() { char *foo = "outer"; for (;; printf(foo),exit(0)) char *foo = "inner"; } which should, in fact, print "inner"[1]. I don't currently have accesss to the C++ processor; does anyone know whether these two examples in fact work correctly for it? Frank Adams ihnp4!philabs!pwa-b!mmintl!franka Multimate International 52 Oakland Ave North E. Hartford, CT 06108 [1] Actually, my example may be an illegal multiple definition of foo. In this case, try it with the "outer" declaration removed.
karl@haddock (09/19/86)
mmintl!franka (Frank Adams) writes: >In C++, one may instead write >main() { > char *foo = "outer"; > for (;; printf(foo),exit(0)) char *foo = "inner"; >} >which should, in fact, print "inner"[1]. I don't currently have accesss to >the C++ processor; does anyone know whether these two examples in fact work >correctly for it? >[1] Actually, my example may be an illegal multiple definition of foo. In >this case, try it with the "outer" declaration removed. Or just move the outer declaration to outside the function; then it should compile in any case. On a related note -- after I apologized for posting that blooper in the first place, I pointed out that the for-while equivalence SHOULD be written for (e1;e2;e3) s --> { e1; while (e2) { s e3; } } with the outer braces necessary to make "if (e0) for (e1;e2;e3) s" have the right semantics. Given this, it seems to me that in the code fragment for (int i=0; i<N; ++i) f(i); the variable "i" should go out of scope at the end of the "for". Last I heard (I don't have a C++ handy either), this was not the case. Has this been changed? Even without the for-while equivalence, I think it's better to have the variable go out of scope. Otherwise why would it be declared as part of the statement rather than in front of it? Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint