tags:

views:

274

answers:

5

In recursive function, the variable should be declared as local or static or global variable?

Thanks in advance...

+1  A: 

Local only.

The recursion method can be defined in a way that passes it's variables with each call. And the final return value is calculated using previous recursion return vars. such as return rec(i-1)+rec(i-2)

If you use global variables, if you run parallel two or more recursion the variables can be messed up.

I advise you to write your recursion to use local variables and in params only.

Pentium10
Lol, looks like you wandered into a maelstrom of confusion…
Potatoswatter
A: 

Using a local variable, you would have to pass this along and return with each recursive call.

Static and global variables can be reached from within any level of the recursion.

astander
Thanks..............
A: 

U can use any of the mentioned ones but everything depends on what u supposed to with recursion !!

Jasim
+7  A: 

It depends. A static variable means you have one variable that's shared across all recursive invocations. A normal local variable means each recursive invocation gets its own copy of that variable. You need to choose the one that makes sense for what you're doing.

A global is like a static local variable (one variable shared by all invocations) but it's also visible to the rest of the application.

Jerry Coffin
I would add that using global variables is bad programming style. No matter where and how they are being used. Static variables may also cause bugs that are tricky to understand.
Lauri
... *especially* in recursive functions.
Greg Hewgill
A: 

It depends what you want to do. Usually I would avoid static.

fastcodejava