🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #2399

Re: Initialization of automatics within loops

#2399
From: Tom Chatt
Date: Tue, 12 Feb 1991 02:02
39 lines
2394 bytes
In article <1991Feb5.023809.389086@locus.com> geoff@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@flood.com           \    Speak up. When we remain silent,
UUCP: ...!uunet!flood!tom        / \     we oppress ourselves.
Technical Details
Message-ID: <1991Feb12.020210.6485@flood.com>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!samsung!spool.mu.edu!uunet!flood!tom
References: <1991Feb5.023809.389086@locus.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!samsung!spool.mu.edu!uunet!flood!tom
From: tom@flood.com (Tom Chatt)
Newsgroups: comp.std.c,comp.lang.c,comp.windows.x
Subject: Re: Initialization of automatics within loops
Message-ID: <1991Feb12.020210.6485@flood.com>
Date: 12 Feb 91 02:02:10 GMT
References: <1991Feb5.023809.389086@locus.com>
Sender: root@flood.com (Operator)
Followup-To: comp.std.c
Distribution: comp.std.c
Organization: The Flood Group, Inc.  Lawndale, Ca.
Lines: 39