-2

I have code like this below:

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("hello");

    while(1){
        // whatever here
    }
}

and the question is: why the first instruction is skipped? It runs only the loop, hello is never printed. I compiled it with gcc and g++ with the same result.

NathanOliver
  • 150,499
  • 26
  • 240
  • 331
Daniel Kucal
  • 6,651
  • 3
  • 33
  • 52
  • 2
    Good question. Complete with full enough source code and a easily understandable question. (+1) – pmg Feb 24 '16 at 15:55

2 Answers2

5

It does run, it's just that the output buffer is not flushed before your while.

Use printf("hello\n"); instead. The newline character will flush the buffer so writing the output immediately to your console.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
3

Your assumption is wrong, your code does run, only stdout is not flushed, but buffered.

Use fflush(stdout) after printf("hello"), this forces stdout to be printed.

And, as @Bathsheba pointed out, also a newline character ("\n") within the printf forces it to flush, which is explained in this SO question.

Community
  • 1
  • 1
Markus Weninger
  • 8,844
  • 4
  • 47
  • 112