Question

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void delay(double sec)
{
    clock_t start = clock();

    while ((clock() - start) / CLOCKS_PER_SEC < sec)
        ;       
}

int main()
{
    for (int i = 0; i < 100000; i++) {
        printf("%d  ", i);
        delay(1);
    }

    return 0;
}

I wrote a delay function and tested it with this code, but I didn't see any number in standard output.

Then I changed the printf() call like this :

printf("%d \n", i);

Interestingly, it worked. I also tried without delay function like this:

    for (int i = 0; i < 100000; i++)
        printf("%d  ", i);

It also worked. What am I missing here? Why can't I see any number when I run the first code? Thanks for helps :)

Was it helpful?

Solution

Because the output is buffered. Most terminals will buffer the standard-output until either a newline (\n) is encountered, or fflush(stdout) is called.

Your loop that includes the call to delay should eventually print the numbers, but when the program is finished.

Add fflush(stdout); after the printf-call to make the numbers appear immediately without newlines in between.

OTHER TIPS

Well, there are two reasons. First, printf() doesn't always flush its output, so you may actually get past the printf statement and still not see anything on your terminal. The text is buffered. Putting in a \n may have caused it to flush its output, so that's why that worked.

The second problem is that you are not passing any value to your delay() function. So it's probably using some random value, and hanging.

I'd also like to point out that clock() returns CPU time, not "wall clock" time, so it may actually take longer than you think.

Delay functions are tricky, that's why there are lots of system calls to do them. See sleep().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top