Path: utzoo!mnetor!uunet!mcvax!ukc!stc!root44!cdwf
From: cdwf@root.co.uk (Clive D.W. Feather)
Newsgroups: comp.lang.c
Subject: Re: How are local vars allocated?
Message-ID: <488@root44.co.uk>
Date: 1 Dec 87 08:57:49 GMT
References: <10572@brl-adm.ARPA>
Reply-To: cdwf@root44.UUCP (Clive D.W. Feather)
Organization: Root Computers Ltd, London, England
Lines: 53

In article <10572@brl-adm.ARPA> I1090801%DBSTU1.BITNET@CUNYVM.CUNY.EDU writes:
>I think there is a good reason for a C-compiler to allocate
>space for all local variables at the beginning of a function.
>Look at the following example:
[Example involving jumping out of one block with 'a' declared, and into
another block with 'b' declared]
>In this case it is not possible to allocate the same space
>for the variables a and b. If you allocate space for a at the
>start of the then-block there is no space allocated for variable
>b after you do the jump into the else-part (at least not until
>the compiler does some very tricky code generation).
On the contrary, a only exists in the then-block, and b in the else-block.
When you jump out of a block, all variables declared in it cease to exist.
When you jump into a block, all variables declared in it come into existence
(though they may not have been initialised correctly).

For example, the code:

main ()
{
   /* Some code, #1 */
   goto label;
   /* Some code, #2 */
   {
      int x = 72;
      /* Some code, #3 */
     label:
      /* Some code, #4 */
   }
}

has the same semantics as:

main ()
{
   int j_label;
   /* Some code, #1 */
   { j_label = 1; goto label; }
   /* Some code, #2 */
   j_label = 0;
   label:
   {
      int x;
      if (j_label) goto label_2;
      x = 72;
      /* Some code, #3 */
      label_2:
      j_label = 0;  /* In case we ever come back again */
      /* Some code, #4 */
   }
}

[Yes, I know this looks terrible. Serves you right for using goto.]