Unusual behavior with printf with an infinite while loop

When I run the program below, I get no output.

#include <stdio.h> int main() { printf("hello"); while(1) { } return 0; } 

whereas if I edit the printf command to add the character '\ n' to the end of the line, then the expected output will appear. what happens in the first code? I just do not understand.

+6
source share
4 answers

This is because stdout is a string buffer, i.e. the output is not written to the device (terminal) until a complete line is collected.

You can call fflush(stdout); to force flush the buffer to the terminal. Do not try to flush stdin , by the way, this is not allowed.

+10
source

try

 printf("hello\n"); 

or

 printf("hello"); fflush(stdout) 
+2
source

You should print a new line at the end of the output. Otherwise, it will invoke undefined behavior (at least potentially undefined).

0
source

Use printf("hello\n");

See the answers to this question for more information.

0
source

Source: https://habr.com/ru/post/955567/


All Articles