Declaration within a loop.

Tim Olson tim at cayman.amd.com
Thu Sep 28 05:11:03 AEST 1989


In article <559 at crdos1.crd.ge.COM> davidsen at crdos1.UUCP (bill davidsen) writes:
| In article <30174 at news.Think.COM>, barmar at kulla (Barry Margolin) 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
| |  implementations will actually use the same memory location (probably
| |  on the stack) each time. 
| 
|   Most C compilers allocate space on the stack for this when the
| procedure is entered. It therefore is not a practical thing to do to
| save space. The most common use is to correct for having forgotten to
| declare a variable at the start of a procedure.

But sometimes it is better to declare the variable in the block to
limit its scope rather than to make every variable visible to the
entire function.  For example, say I want to debug a function by
printing out a linked list at a certain point.  I can say something
like:

	.
	.
#ifdef DEBUG
	{
		struct list *p;
		for (p=my_list; p; p=p->next)
		    printf("\t%d\n",p->value);
        }
#endif

and I have limited my changes to one area.


	-- Tim Olson
	Advanced Micro Devices
	(tim at amd.com)



More information about the Comp.lang.c mailing list