tags:

views:

222

answers:

3

I have command line utility written in ANSI C on a Mac with a function to create a bubble sorted array for a single-linked list. I declared the loop variables.

int a = 0;   
int b = 0;

I wrote the bubble sort for loops in the abbreviated style (i.e., leaving the variable initialization empty).

for ( ; a < size; a++)  
  for( ; b < size; b++) 

This executed only once before exiting. A previous for loop using the i variable to populate the array was written the same way and executed as expected. The fix for the bubble sort loops was to put a = 0 and b = 0 back in. Is there a reason why the abbreviated for loops failed to execute?

+1  A: 

A different for loop to populate the array was written the same way and executed as expected.

It sounds like this was before the current loop, and used the same variables a and b.

And didn't reset them back to zero afterwards.

Anon.
I edited the text. The previous for loop used the i variable.
C.D. Reimer
+11  A: 

If you leave out the b=0 the inner loop will run exactly once, because after that b is already equal to size. You need to reset b to 0 on each iteration of the inner loop.

sepp2k
That's the answer. I tested this with my code. The inner loop wasn't being reset to zero when the outer loop restarted. Thanks!
C.D. Reimer
+2  A: 

Why do you want to use what you call the abbreviated style of for loop ?

for loops are merely syntaxic sugar for the while loop below:

for (INIT ; ENDTEST ; STEP){
    DO_SOME_STUFF
}

means

INIT
while (ENDTEST) {
 DO_SOME_STUFF
 STEP
}

Hence your two loops are doing:

int a = 0;
int b = 0;
while (a < size){
   while (b < size){
      DO_SOME_STUFF
      b++;
   }
   a++;
}

In this form you can easily see that initialization of b is not done where it should.

All I could say is to avoid using abbreviated for loops, removing the initialization is no better than removing the end test or removing loop step (both are also legal in C) all are easy ways to put bugs in your programs. Just don't do it.

kriss
`for` loops are not quite equivalent to `while` loops in that way. A `continue` statement in the loop body does different things in each case.
jamesdlin
You're right, a continue statement execute step in for loops, not in the above while.
kriss