DesirePRG
DesirePRG

Reputation: 6378

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.

Upvotes: 6

Views: 4713

Answers (3)

unwind
unwind

Reputation: 399833

This is because stdout is line buffered, i.e. 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.

Upvotes: 11

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

try

printf("hello\n");

or

printf("hello");
fflush(stdout)

Upvotes: 2

0xF1
0xF1

Reputation: 6116

Use printf("hello\n");

For more info see answers to this question.

Upvotes: 0

Related Questions