Afficher un message
Vieux 13/04/2008, 22h14   #6
Malcolm McLean
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: local variables in a recursive program


"Keith Thompson" <kst-u@mib.org> wrote in message
> If you want a single copy of a variable for all invocations of a
> function, use "static". If you want a separately allocated copy for
> each invocation, don't use "static". Recursion has very little to do
> with the choice.
>

Conside this simple function

void zero(NODE *node)
{
int i;

for(i=0;i<node->N;i++)
node->x[i] = 0;
}

it would be very confusing to make i static, though almost harmless - you
gobble an extra few bytes of memory.

Now let's make it recursive

void zeror(NODE *node)
{
static int i;

if(!node)
return;
for(i=0;i<node->N;i++)
node->x[i] = 0;
zeror(node->left);
zeror(node-<right);
}

now there is a point in making i static. Unless the compiler is extremely
good it won't realise that a separate instance of i is not required for each
call. So we can handle a rather deeper tree than if i is automatic.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

  Réponse avec citation
 
Page generated in 0,04574 seconds with 9 queries