-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
  • 161,918
  • 27
  • 262
  • 366
Daniel Kucal
  • 7,692
  • 4
  • 36
  • 59
  • 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
  • 227,678
  • 33
  • 352
  • 470
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
  • 10,693
  • 6
  • 57
  • 121