0

I am beginner in C programming. I don't understand one thing. Why if I put down that

printf("write down any whole number:");
scanf("%d",&(any int variable));

When I use gdb(debugger) it shows me that CPU executes printf(), but doesn't write anything, then goes to the scanf() instruction and after that writes String and takes it to analyze by scanf function.

I am using GCC and Linux Debian

Question: Why printf is executed only after scanf?

Thank you.

Beso
  • 1,176
  • 5
  • 12
  • 26
  • I'm not sur why, something probably done by the optimisation, but to resolve this you can use an `fflush()` to print it – Mike Gerard Oct 17 '21 at 17:10

1 Answers1

3

As you saw in the debugger — and great that you used one as a beginner! — the printf has been executed alright. The characters are now in a buffer which will be flushed when a newline is output or the buffer is full which may happen at 4096 bytes, or some other amount, often a power of 2. The reason for the buffering is efficiency: The actual transfer to the terminal is slow. If it happened for every single character it would be unnecessarily slow. The fix is to print a newline, or flush explicitly with flush.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
  • Thank you very much. It blew up my mind when I write printf("hello"); then I added a loop and it turned out that printf was executed after loop. ))))) –  Oct 17 '21 at 18:33
  • I mean "printf was executed after loop" not executed, but flushed –  Oct 17 '21 at 18:37
  • Reading the linked answer I realize that my answer is only half the truth: Even without the newline your text should appear before the program waits for input at scanf; this is specified exactly for this use case. So, what I wrote is not wrong but the interesting question is just *why* the buffer is not flushed before the scanf, as it should be. It could be that you use an IDE which displays the output e.g. in a text window or such. For some reason the standard output connected to the program running in the IDE does not identify itself as a terminal (i.e., `isatty(fd)` returns 0). – Peter - Reinstate Monica Oct 18 '21 at 07:08
  • Thank you. I read linked answer too. And I got it))). But you gave me the main idea))) –  Oct 18 '21 at 08:38