Declaration within a loop.
Conor P. Cahill
cpcahil at virtech.UUCP
Thu Sep 28 02:04:27 AEST 1989
In article <30174 at news.Think.COM>, barmar at kulla (Barry Margolin) writes:
> In article <2085 at hydra.gatech.EDU> dvu at prism.gatech.EDU (Dinh Vu) writes:
> > do {
> > int i;
> > ........ ;
> > } while (1);
> >Is it true that every time through the loop, a new i variable
> >is declared (more memory allocated ??)?
>
> 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:
int main()
{
int fd;
char *p;
char t;
extern char *ttyname();
int i;
for(i=0; i < 10; i++)
{
char buffer[50];
printf("buffer = 0x%x\n",buffer);
}
}
The following assembly code is generated (using "cc" on 386/ix):
.globl main
main:
jmp .L54
.L53:
movl $0,-16(%ebp) /* i = 0 */
jmp .L58
.L59:
leal -66(%ebp),%eax /* get address of buffer */
pushl %eax /* put on stack for printf */
pushl $.L60 /* put string on stack */
call printf /* call printf */
addl $8,%esp /* clean stack */
incl -16(%ebp) /* i++ */
.L58:
movl $10,%eax /* get 10 for comparison*/
cmpl %eax,-16(%ebp) /* compare i to 10 */
jl .L59 /* I < 10 ? */
.L57:
.L52:
leave
ret
.L54:
pushl %ebp
movl %esp,%ebp
subl $68,%esp
jmp .L53
.def main; .val .; .scl -1; .endef
.data
.L60:
.byte 0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x3d,0x20,0x30
.byte 0x78,0x25,0x78,0x0a,0x00
Note that at .L54 the data is allocated ONCE and only once. It is not
allocated/deallocated for each iteration. This is unoptimized assembler
source generated using the -S flag.
--
+-----------------------------------------------------------------------+
| Conor P. Cahill uunet!virtech!cpcahil 703-430-9247 !
| Virtual Technologies Inc., P. O. Box 876, Sterling, VA 22170 |
+-----------------------------------------------------------------------+
More information about the Comp.lang.c
mailing list