简体   繁体   中英

unusual behaviour with printf with infinite while loop

When I run the below program, I do not get any output.

#include <stdio.h>

int main()
{
    printf("hello");
    while(1)
    {

    }   
    return 0;
}

whereas if i edit the printf command to add a '\\n' character to the end of the string, then the expected output comes. what is going on in the first code? I simply cannot understand it.

This is because stdout is line buffered , ie the output is not written to the device (the terminal) until a full line has been collected.

You can call fflush(stdout); to force a flush of the buffer to the terminal. Do not try to flushing stdin by the way, that's not allowed.

try

printf("hello\n");

or

printf("hello");
fflush(stdout)

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

Use printf("hello\\n");

For more info see answers to this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM