0

I am learning C and currently trying to understand why in the code part below the while loop is executed before the for loop!?

The code should display a 3-digit random number and then wait n seconds.

srand(time(NULL));
time_t rnd_number_length = 3;
for (int i=0; i < rnd_number_length; i++) {
    printf("%d ", rand() % 10);
}

clock_t waiting_time = clock() + 5 * CLOCKS_PER_SEC;
while(clock() < waiting_time) {}

However, when I compile and run this code, the program waits first and only then displays the random digits. Why is this happening?

minerals
  • 6,090
  • 17
  • 62
  • 107
  • 2
    Why is `rnd_number_length` of type `time_t`? – Emanuel P Apr 19 '21 at 06:36
  • 7
    The output stream is buffered. You have to `fflush` it. – Emanuel P Apr 19 '21 at 06:37
  • It can be of type int, but does it have anything to do with the execution order ;) ? – minerals Apr 19 '21 at 06:37
  • There are a lot of mistakes in books. It's also possible that behavior has changed since the book was written. – Retired Ninja Apr 19 '21 at 06:46
  • 5
    Note: adding `\n` to the `printf` format specifier will send a cr/lf which will also flush the output – Paul Ogilvie Apr 19 '21 at 06:47
  • `while(clock() < waiting_time) {}` is called [polling](https://en.wikipedia.org/wiki/Polling_(computer_science)) and is a **very bad** way to wait because it'll consume 100% CPU. You must use a timer or the system's sleep function to do that – phuclv Apr 19 '21 at 09:40
  • See also https://en.wikipedia.org/wiki/Busy_waiting#Busy-waiting_alternatives, [Why do blocking functions not use 100% CPU?](https://stackoverflow.com/q/23108140/995714), [C Main Loop without 100% cpu](https://stackoverflow.com/q/1222574/995714) – phuclv Apr 19 '21 at 09:49

0 Answers0