0

I have the following snippet of code:

foo();
std::cout << "Foo";
loop();

Where loop is a function that does not terminate because it runs into some infinite loop (not intentional). However, it seems like my program is running into the infinte loop without printing the output ("Foo"). Is the compiler allowed to change the behavior of the code in this way?

Neither foo() nor loop() interfere with standard output.

Unfortunately, I cannot give more specific information about the setup. So I just want do know whether there needs to be a bug (in code or compiler) before the call of loop() or if the compiler is allowed to assume that later code is bugfree?

Edit: The reason for this behavior is probably a missing std::flush. The original question is therefore not that interesting for me anymore (but it probably is still a question one can ask).

Henk
  • 826
  • 3
  • 14
  • 2
    Maybe you need [to flush](https://en.cppreference.com/w/cpp/io/manip/flush) the `cout` stream ? – wsdookadr Jan 24 '21 at 10:43
  • Yes, that could be the reason. Thanks! – Henk Jan 24 '21 at 10:47
  • Putting `endline` guarantees to flush, otherwise it may or may not flush. Or you can force to flush. – Kao Jan 24 '21 at 10:49
  • 1
    What is the proper way to handle this question now? It is probably already answered. – Henk Jan 24 '21 at 10:49
  • Additionally unlike `cout`, `cerr` does not accumulate outputs in buffer, it flushes directly. – Kao Jan 24 '21 at 10:53
  • 1
    You can disable `stdout` and `cout` buffering with `std::cout.setf(std::ios::unitbuf);` https://stackoverflow.com/a/1377101/2928168 – emi Jan 24 '21 at 11:04
  • `cout` is buffered by default. Unless something interact with it, the data in the buffer will not be written to standard output. Simply write `std::cout<<"foo"< – Michael Doubez Jan 24 '21 at 11:04
  • @Kao That wouldn't print the same thing (since `endl` also adds `\n`). – Ted Lyngmo Jan 24 '21 at 11:04
  • I do not agree with closing the question due to duplicate reasons. The answer might be a duplicate of another question, but not the question. Or is there another meaning of [duplicate]? – Henk Jan 24 '21 at 11:10
  • "Your post has been associated with a similar question. If this question doesn’t resolve your question, ask a new one." <- This is not what is happening here, so I think that this is abuse of [duplicate]. Of course, it somehow makes sense to link the other answer, but this "hack" does not seem to be the proper way. For example, it neglects the reputation for the one who figured out the problem. – Henk Jan 24 '21 at 11:14
  • @Henk Maybe that wasn't the best choice of duplicate. But there are so many that deal with the `cout` buffering issue. If you find a better (or alternative) post, link it here and ping me, and I can edit the close banner. – Adrian Mole Jan 24 '21 at 11:24

0 Answers0