tags:

views:

208

answers:

4

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

I compiled the program with gcc:

#include<stdio.h>

main()
{
    printf("hai");
    for(;;);
}
+9  A: 

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
Why the downvote? Failure to include `return 0` from a function that never returns?
Sinan Ünür
you didn't even fix his include typo...
faceless1_14
I downvoted because what you have doesn't compile.
faceless1_14
I took away the downvote because your answer is now correct.
faceless1_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
+3  A: 

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
+4  A: 

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)

Adriaan
+2  A: 

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.

anon