Is printing an empty string observable behavior in C++?
In C++03 Standard observable behavior (1.9/6) inc开发者_Python百科ludes 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?
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.
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
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.
In theory, you C library can be written in a way that flushes the buffer based on time. In that case, printing of empty string can result in a flush, thus producing a visible effect.
Of course this has observable behavior - it must generate a call to write() system call with the underlying file descriptor. Making a system call is very observable behavior.
Consider as an extreme example that the file descriptor in the kernel may be serviced by a device driver that sounds siren every time it's write file operation is called (OK, somewhat of an artificial example, I'll admit :-) ...
精彩评论