• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with recursion

 
mario tan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

Ive read an article which talks about recursion and I find it very interesting. However my mind boggles everytime I read the code from this article:

Connect 4 recursion

Please take time to look at the code..

You can see there that each time the method best_move is called, there is always that declaration and instantiation of best_score.

best_score is an instance of MoveValue.

Since this is a recursive method, will each call to the method best_move have its own copy of best_score? That means that there could be plenty of MoveValue object that will reside on the heap having only one name which is best_score?

I've tested the code but the best_move always return a MoveValue object with score = 0 and col = 6.

Why is that so?.. Can someone please explain to me the code and how to correctly trace it? Thanks in advance.


Best regards,

Mario
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12100
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't look at the code, but the answer is probably yes.

when a method is called, any method variables get created. it doesn't matter who calls the method, a new set get created.

so, if you have a method call itself, the top level will have a copy, the next level will have its own copy, and so on, all the way down.

technically, object on the heap do not have names. if your method has a "best_score" variable, you actually have two things. you have the object itself that lives on the heap, and the REFERENCE named "best_score". the reference lives on the stack, and knows where its best_score object lives. each new 'best_score' reference hides all the previous ones, and the current one points to the current object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic