local variables in a recursive program

P

pereges

In a recursive program, do you think it is necessary to add the static
keyword for every variable or do you think it is unnecessary ? Is
every call associated with seperate copy of variables ?
 
K

Keith Thompson

It is probably necessary to *REMOVE* the static keyword for most
of the variables.


If you use static, you get *one* copy of the variable for all of the
calls *combined*. This is not what you want for a recursive program,
although static read-only variables are not a problem.

That may or may not be what you want. It depends on what you're
doing.

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.

If you find yourself using "static" a lot, re-think what you're doing;
the vast majority of variables declared within functions should *not*
need to be static.

Note: Gordon deliberately and rudely deleted the attribution line for
"pereges", as he always does. I've re-inserted it. I do not grant
permission to quote this or any other article I post to Usenet without
attribution.
 
W

Willem

Malcolm wrote:
) void zeror(NODE *node)
) {
) static int i;
)
) if(!node)
) return;
) for(i=0;i<node->N;i++)
) node->x = 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.

If the compiler is even remotely decent it will put i in a register and
never allocate memory for it in the first place. Making it static might
prevent that from happening.


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top