Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would C get stuck halfway through a while loop?

Tags:

c

while-loop

When I compile and run this code (it's part of a much larger program), Linux gets halfway through the while loop, then simply stops working.

The code below prints time: 0 and then hangs, doing nothing else until I suspend the process. Why on earth would it print time: 0 but not the following line of sanity check?

while (i < 5)
{
    printf("time: %d\n",elapsedTime);
    printf("sanity check");
    foo();
    i++;
}
like image 669
Raven Dreamer Avatar asked Feb 26 '11 03:02

Raven Dreamer


1 Answers

Output usually is buffered and only written after a flush or newline. In

printf("sanity check");

there is no newline, so if you run in an endless loop after this, you won't see it. Replace it with

printf("sanity check\n");

or

printf("sanity check");
fflush(stdout);

and you'll see it.

like image 72
schnaader Avatar answered Nov 16 '22 02:11

schnaader