Declaration within a loop.

Sean Fagan seanf at sco.COM
Fri Sep 29 11:58:33 AEST 1989


In article <1199 at virtech.UUCP> cpcahil at virtech.UUCP (Conor P. Cahill) writes:
>> Yes, a new i variable is declared.  However, at the end of each time
>> through the loop it is "undeclared", so it can be deallocated.  Most C
>
>I disagree.  Using the following source code:

You are also wrong.  Since you felt like posting source code, I think I will
do the same.  What do you expect the following code to do, when compiled and
run?

	static int x = 0;
	int foo() { return x++; }

	main() {
		int a;
		for (a=0; a< 100; a++)
		{
			int b = foo();
			printf ("b = %d\n", b);
		}
		return (0);
	}

If 'b' is not created each time, then foo() is only called once.  However,
you will note that it *isn't* called just once.

To explain (sort of) the results you got:  in the following fragment,

	for (a=0; a< 100; a++)
	{
		int b;
	}
	for (a=0; a< 200; a++)
	{
		int c;
	}

would you be surprised if &b == &c?  I wouldn't; and, in your example,
that's what was happening.  The compiler knew it could reuse the space, and
did so.  Did so so well, in fact, that it never touched the stack pointer
in-between the loops.

Anyway, that's what dmr says, so it must be right 8-).

-- 
Sean Eric Fagan  | "Time has little to do with infinity and jelly donuts."
seanf at sco.COM    |    -- Thomas Magnum (Tom Selleck), _Magnum, P.I._
(408) 458-1422   | Any opinions expressed are my own, not my employers'.



More information about the Comp.lang.c mailing list