0

The following C program doesn't printing anything on the screen.

I compiled the program with gcc:

#include<stdio.h>

main()
{
    printf("hai");
    for(;;);
}
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Binu
  • 1,365
  • 5
  • 14
  • 23

4 Answers4

9

Most likely, stdout is line buffered. Your program does not call fflush or send a newline so the buffer does not get written out.

#include <stdio.h>

int main(void) {
    printf("hai\n");
    for(;;)
    ;
    return 0;
}

See also question 12.4 and What's the correct declaration of main()? in the C FAQ.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • Why the downvote? Failure to include `return 0` from a function that never returns? – Sinan Ünür Aug 11 '09 at 13:14
  • @faceless I had missed the typo originally. Human brains are like that: They do automatic error correction when you least want them to. It would have been nice of you to point out that I had missed the typo when you downvoted my answer. – Sinan Ünür Aug 11 '09 at 13:31
4

This is caused by the buffering which takes place in stdio (i.e. it is not output immediately unless you tell it to by including a \n or fflush). Please refer to Write to stdout and printf output not interleaved which explains this.

(p.s. or the compiler is not happy about the typo in #include)

Community
  • 1
  • 1
Adriaan
  • 3,282
  • 1
  • 23
  • 31
3

Standard output tends to be line buffered by default so the reason you're not seeing anything is because you haven't flushed the line.

This will work:

#include <stdio.h>
int main (int argC, char *argV[])
{
    printf("hai\n");
    for(;;)
        ;
    return 0;
}

Alternatively, you could fflush standard out or just get rid of the infinite loop so the program exits:

#include <stdio.h>
int main (int argC, char *argV[])
{
    printf("hai");
    return 0;
}

but you probably want the newline there anyway.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

Your for(;;) loop stops the stream from being flushed. As others have suggested, add a newline to the string being output, or flush the stream explicitly:

fflush( stdout );

after your printf. And correct the spelling of #include.