C.D. Reimer
C.D. Reimer

Reputation: 115

C - Abbreviated for loop executed only once

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?

Upvotes: 2

Views: 1566

Answers (3)

kriss
kriss

Reputation: 24157

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.

Upvotes: 2

sepp2k
sepp2k

Reputation: 370112

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.

Upvotes: 11

Anon.
Anon.

Reputation: 59973

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.

Upvotes: 1

Related Questions