2

I have a recursive function which runs through a quadtree and generates for each node a key. But this only works when I save the variable myKey as myKey1. If I do not do that, the resulting keys are wrong. But why? That is not clear to me.

Here is the function:

void keygen(tree *tn, long unsigned int myKey)
{
    long unsigned int myKey1 = myKey; // Why do I need this line?

    for(int q=0; q<4; q++){
        // 1) Check if child exists
        if(tn->child[q] != NULL){
            // Make key
            myKey1 = (myKey<<DIM)|q;
            // Save key
            tn->child[q]->key = myKey1;
            // Call again if leaf               
            if(tn -> child[q] -> isLeaf == 0){ 
                keygen(tn->child[q], myKey1);
            }
        }
    }   
}
4
  • 5
    Because of the line myKey1 = (myKey<<DIM)|q;? If you were originally using myKey on the left and right, you'd be accumulating shifts on every iteration of the loop. Commented Dec 5, 2016 at 17:53
  • 1
    @happydave: Why not make this an answer? Commented Dec 5, 2016 at 17:59
  • @happydave Yes, now I see it. You are totally right! Thank you! Commented Dec 5, 2016 at 18:08
  • @alk: Mostly because I didn't have time to read the code carefully enough to be confident that this was the real issue. I guess I'll turn it into an answer now Commented Dec 5, 2016 at 21:06

1 Answer 1

2

This line is likely the issue

myKey1 = (myKey<<DIM)|q;

If you don't make a separate myKey1 variable, then you'll be shifting by DIM on every iteration of the loop, so by the fourth iteration, you'll have shifted by 4*DIM (and bitwise-ORed with various values of q between shifts).

It seems like your intent is to just shift and or once relative to the original key, which is what you accomplish by creating a new variable rather than modifying the original myKey in place.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.