6

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.

DesirePRG
  • 6,122
  • 15
  • 69
  • 114
  • call `fflush(stdout)` btw you have infinite loop. – Grijesh Chauhan Oct 09 '13 at 11:18
  • 3
    Output is buffered. You need either a `\n` at the end of the string to get it to print out, or use `fflush(stdout)` after your `printf` as @GrijeshChauhan suggested. There are other operations which flush the output buffer as well, such as an input function (`getchar` or `scanf`) but it's unclear from your code snippet what your loop is doing. – lurker Oct 09 '13 at 11:20
  • possible duplicate of [Why does program not execute final printf statement?](http://stackoverflow.com/questions/11277796/why-does-program-not-execute-final-printf-statement) – lurker Oct 09 '13 at 11:22

3 Answers3

11

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • ok but why does the code work without the infinite loop and with the same printf as above then? – DesirePRG Oct 09 '13 at 11:22
  • 3
    When program terminates shortly after, the os would definitely flush output buffer sooner as opposed to no flush request and program being continued. – fkl Oct 09 '13 at 11:23
2

try

printf("hello\n");

or

printf("hello");
fflush(stdout)
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
0

Use printf("hello\n");

For more info see answers to this question.

Community
  • 1
  • 1
0xF1
  • 6,046
  • 2
  • 27
  • 50