Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is printing an empty string observable behavior in C++?

In C++03 Standard observable behavior (1.9/6) includes calls to library I/O functions. Now I have this code:

printf( "" );

which is formally a call to a library I/O function but has no effect.

Is it observable behavior? Is the compiler allowed to eliminate it?

like image 356
sharptooth Avatar asked Aug 26 '11 14:08

sharptooth


3 Answers

It's certainly observable if sync_with_stdio is true. When that's true, printf("") forces synchronization with std::cout output, flushing previously buffered output.

like image 150
MSalters Avatar answered Oct 15 '22 05:10

MSalters


It would observable

  • if the output is redirected and the file was closed, truncated, or somehow has become invalid for output
  • if the stream state was 'bad' anyway

The point made about sync_with_... is also very relevant

like image 30
sehe Avatar answered Oct 15 '22 05:10

sehe


I highly doubt it, since the behavior might become more highly visible in multithreaded programming if the OS chooses to context switch when the thread invoking printf blocks for I/O.

In that case, it will definitely have an effect if the results depend on how the threads is interleaved.

like image 27
Platinum Azure Avatar answered Oct 15 '22 03:10

Platinum Azure