Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!uunet!virtech!cpcahil From: cpcahil@virtech.UUCP (Conor P. Cahill) Newsgroups: comp.lang.c Subject: Re: Declaration within a loop. Message-ID: <1199@virtech.UUCP> Date: 27 Sep 89 16:04:27 GMT References: <2085@hydra.gatech.EDU> <30174@news.Think.COM> Distribution: usa Organization: Virtual Technologies Inc Lines: 76 In article <30174@news.Think.COM>, barmar@kulla (Barry Margolin) writes: > In article <2085@hydra.gatech.EDU> dvu@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 | +-----------------------------------------------------------------------+