Initialization of automatics within loops
Tom Chatt
tom at flood.com
Tue Feb 12 13:02:10 AEST 1991
In article <1991Feb5.023809.389086 at locus.com> geoff at locus.com (Geoff Kuenning) writes (paraphrases in brackets):
> [ In the following example (drawn from actual Xlib code): ]
>
> main ()
> {
> int i = 0;
> while (i < 3)
> {
> int j = 4;
> printf ("i = %d, j = %d\n", i, j);
> i++;
> j++;
> }
> }
>
> [ Does the initialization of j=4 occur at the start of each iteration
> of the compound statement, or only the first iteration? Mr. Kuenning's
> compiler sets j=4 each time; the X programmer evidently expected otherwise.
> The ANSI C standard says that automatics are initialized on every entry
> to a compound statement, but does the above example count as three
> entries to the compound statement, or only one? ]
WRT entering the compound statement, it seems pretty clear to me that
the compound statement is re-entered at each iteration, and that the
initialization (as per spec) should occur each time. I say this because
the test "i < 3" is clearly outside of the compound statement, and this
executes at each iteration, thus you must have exited the compound statement.
Though a compiler *may* optimize this out, it would be perfectly
correct for a compiler to *allocate* the automatic variable at each
entry to the compound statement. In the example above, the programmer
has some expectation about the value of the automatic variable persisting
outside of its scope (i.e., between iterations). This practice is
extremely dubious and inadvisable. If a programmer expects a variable's
value to persist outside of its scope, he should declare it as static.
--
Tom Chatt \ Don't take offense, take action.
Internet: tom at flood.com \ Speak up. When we remain silent,
UUCP: ...!uunet!flood!tom / \ we oppress ourselves.
More information about the Comp.lang.c
mailing list