for != while
Mike Beckerman
mikeb at copper.UUCP
Thu Sep 4 01:25:08 AEST 1986
In article <15525 at ucbvax.BERKELEY.EDU> ballou at brahms.UUCP (Kenneth R. Ballou) writes:
>In article <86900030 at haddock> karl at 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".
More information about the Comp.lang.c
mailing list