Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Could somebody help me out with this problem please? I am trying to remove tail recursion in a small routine from
some ancient code
C++
static void new_tristrip(polygon_node **tn, edge_node *edge,
                         double x, double y)
{ polygon_node *temptn,*Stemp;

  #if 0
/* this part is the code i want to work */
    MALLOC(temptn, sizeof(polygon_node), "tristrip node creation", polygon_node);
    (temptn)->next= NULL;
    (temptn)->v[LEFT]= NULL;
    (temptn)->v[RIGHT]= NULL;
    (temptn)->active= 1;
    add_vertex(&(temptn->v[LEFT]), x, y);
    edge->outp[ABOVE]= temptn;
   if(!(*tn))
      tn=&temptn;
   else
     { Stemp=(*tn)->next;
       while((Stemp->next))Stemp=Stemp->next;
        Stemp->next=temptn;
     }
    return;

  #else
/* this is the tail recursive code */
  if (!(*tn))
  {
    MALLOC(*tn, sizeof(polygon_node), "tristrip node creation", polygon_node);
    (*tn)->next= NULL;
    (*tn)->v[LEFT]= NULL;
    (*tn)->v[RIGHT]= NULL;
    (*tn)->active= 1;
    add_vertex(&((*tn)->v[LEFT]), x, y);
    edge->outp[ABOVE]= *tn;
  }
  else
    /* Head further down the list */
    new_tristrip(&((*tn)->next), edge, x, y);
  #endif
}
Posted
Updated 2-May-12 23:40pm
v3

1 solution

Why not simply:

while (*tn)
    tn = &((*tn)->next);

MALLOC (*tn, ...
 
Share this answer
 
Comments
Stefan_Lang 3-May-12 10:14am    
Personally I'd use a local variable for that as the current code does not change tn. The function prototype doesn't declare it as const, but with legacy code you never know what was intended ;)

Otherwise I agree.
nv3 3-May-12 15:32pm    
Hello Stefan. Normally I don't like to use arguments as local variables either; in so far I agree. In this particular case it does make any difference as a pointer is always transferred by value. In this case tn is a pointer to the anchor of the entire tree and we successively step one level down, always having tn point to the cell where the next node is going to be hooked in.

I just wish the author of the question would let us know whether that attempt was successful or not.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900