Print operation will not print until infinite loop

While trying to debug the C code, I noticed that printf () would not execute if placed before an infinite loop. Does anyone know why this is? In practice, this isn't such a big deal, but for debugging her nightmare.

#include<stdio.h>

int main()
{
  int data;

  printf("This prints fine.\n");  

  printf("Enter data: ");
  scanf("%d", &data);

  printf("This should print but it doesn't.\n");

  while(1)
  {
    //Infinite Loop
  }

  return 0;
}

      

+2


source to share


3 answers


When you call printf (), the output is printed after the program terminates or a newline character appears. But since you are calling an infinite loop after printf (), the program does not terminate and the output from the buffer is not displayed.

Use fflush(stdout)

to force buffered output



stdout

The standard output stream is the default destination for applications. On most systems, it is usually directed by default to a text console (usually on screen).

The function makes the system clear the buffer fflush()

+2


source


try __fpurge (stdout) It will clear your output buffer



0


source


This concept is called line buffer and block buffer. Every thing you want to write to the screen will be in a buffer. line buffer means that ever a newline [\ n] found that "ll flush the buffer, which means your line will be printed to the screen. block buffer means they will be a fixed size for a block until that block is will be completely printed to the screen.in the above case, a new line [\ n] is enough to print

0


source







All Articles