1

I have been trying to use fflush to make a progress bar. To test fflush, I wrote the small code below.

It works as it supposed to when I uncomment "sleep(1);" but it works in an unexpected way if it remains commented out. It prints the first dash, waits than prints all remaining 9 of them and quits.

I don't understand why it makes a difference.

int main()
{
    int f,j;
    j =0;
    for(f=0;f<10;f++)
     {
        printf("-");
        fflush(stdout);
        while(j++<1000000000);
        //sleep(1);
     }
}
Nakilon
  • 34,866
  • 14
  • 107
  • 142
yam
  • 1,383
  • 3
  • 15
  • 34

4 Answers4

2

You need to set j back to zero after the while loop. The next iteration it will just skip over the while loop.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
syork
  • 36
  • 3
1

This is because you don't reset the inner loop counter j to zero at each outer loop iteration, i.e. the while() is executed only the first time around. Nothing to so with fflush() :)

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
1

For the first 'for' iteration f=0, it will print the first dash, then will run j up to 1 billion, and then it will print the nine remaining dashes because j is greater than 1 billion hence no more wait or delay. That is how it should run if sleep(1) is commented out.

You may wish to add line j=0; after the while loop to reset j to zero.

When you uncomment sleep(1) there will be a small almost unnoticeable delay (I guess 1 millisecond) after printing each dash.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Only You
  • 2,051
  • 1
  • 21
  • 34
1

Change your for loop like so:

from:

for(f=0;f<10;f++)

to:

for(f=0, j=0; f<10; f++, j=0)
Nakilon
  • 34,866
  • 14
  • 107
  • 142
Ziffusion
  • 8,779
  • 4
  • 29
  • 57