Initialization of automatics within loops

Doug Gwyn gwyn at smoke.brl.mil
Wed Feb 6 06:57:35 AEST 1991


In article <1991Feb5.023809.389086 at locus.com> geoff at locus.com (Geoff Kuenning) writes:
-	    while (i < 3)
-		{
-		int j = 4;
-		printf ("i = %d, j = %d\n", i, j);
-		i++;
-		j++;
-		}
-What does this print?  On the machine I'm using, it prints the same value
-for j (j = 4) three times.  On the other hand, the programmer of XSend()
-clearly expected three different values for j.

The programmer clearly made a mistake.  j has the value 4 for each
execution of the printf().  I was unable to tell from the code
snippet just what the programmer intended; merely changing the
storage class of j to "static" would probably not be correct either.

-I just checked the ANSI C spec on this, and found it unclear.  It is
-explicitly stated that automatics are initialized on every entry to a
-compound statement.  However, it is not made clear whether the construct:
-	while (<expression>)
-	    <statement>
-is considered to *re-enter* the compound statement every time or not.

There is no question whatsoever about this.  The compound statement is
completely evaluated for each iteration; this includes the auto
initialization.



More information about the Comp.std.c mailing list