0

printf debugging. The while loop executes, the 1st for loop executes, the 2nd for loop does not.

while (size > 0){
    printf("in the while loop!\n");
    VertexPointer current = graph[0];
    int i;
    for (i = 1; i < size; i++){
        float dist = 0;
        printf("in the first for loop for i = %d \n", i);
        int j;
        for(j = 0; j++; j < dimension){
            printf("dist loop: %d\n", j);
            printf("current: %f\n", (*current).loc[0]);
            printf("unvisited: %f\n", (*graph[j]).loc[0]);

            dist = dist + pow((*current).loc[0] + (*graph[j]).loc[0], 2);
            printf("distance:  %f", dist);


            dist = sqrt(dist);
            if (dist < (*graph[i]).key){
                decreaseKey(graph, i, dist);
            }
        }

    }

    extractMin(graph, size);
    size = size - 1;
    mst_length = mst_length + (*current).key;
}
1
  • 6
    You switched the condition and increment: j++; j < dimension should be: j < dimension; j++ Commented Mar 7, 2014 at 22:42

1 Answer 1

2

You switched the condition and increment:

for(j = 0; j++; j < dimension)

so the loop tests the value of j++, and since the postfix ++ operator returns the previous value of the variable it increments, it will return 0 (the initial value of j) on the first iteration and thus never loop. Change it to

for(j = 0; j < dimension; j++)

If you turn on warnings you should receive a message that the third expression has no side-effects (and would be optimized-away by the compiler).


Alternatively (stop: don't actually do this):

change the condition to ++j to make it a (potentially) never-ending loop instead:

for(j = 0; ++j; j < dimension)

if you're lucky (which is usually, in this case) the loop will end when j reaches MAX_INT and wraps around to 0. But the standard doesn't guarantee that, so it's potentially endless.

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

2 Comments

Aside from the result of integer overflow being undefined by the standard (in contrary to unsigned overflow), still, in most implementations, it will wrap from INT_MAX to INT_MIN, not to 0.
Which is why I said you'll usually be lucky, but no guarantees.

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.