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(;;);
}
1
  • Yes it doesn't, and what is your question? Commented Aug 11, 2009 at 13:25

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why the downvote? Failure to include return 0 from a function that never returns?
@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.
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)

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.