Decrementing Initialization of a For Loop (C) – EX: for(i–; i>0; i–)

I have been reading about operating system design in the book, "The Xinu Approach 2nd Ed.", and came across a for loop statement in chapter 10 on page 182/183. The for loop starts off decrementing the initialization statement of the for loop. I hadn’t seen this before, so I created my own version of this loop to play around with it, as seen here:

        #include stdio.h
        main(){
          int i = 100;
          for(i--; i>0; i--){
             printf("%d \r", i);
          }
        }

Upon compilation with gcc and running of this small program, the output is: 1. This has confused me quite a bit as I would have expected the for loop to just end up skipping i=99 since the decrement operator is ran after the initialization variable is observed.

The for loop code in Xinu that began my line of questioning has to do with buffer pool creation and essentially loops through a block of memory (pool) to partition it up into separate buffers. The initialization variable, numbufs stands for the number of buffers the user wishes to carve out of the pool. The starting address of the pool is given by buf. Here is the loop for reference:

        for (numbufs-- ; numbufs>0 ; numbufs-- ) {
           bpptr = (struct bpentry *)buf;
           buf += bufsiz;
           bpptr->bpnext = (struct bpentry *)buf;
        }

Can someone please explain how these kinds of for loops work?

>Solution :

In your version of the loop you print the ‘\r’ character. This is a carriage return character. The result is that printf overwrites already written characters. Please see this question: What's the Use of '\r' escape sequence?

Leave a Reply