在 C++ 中打印空字符串是否可观察行为?

发布于 2024-12-01 11:42:49 字数 164 浏览 4 评论 0原文

在 C++03 标准可观察行为 (1.9/6) 中包括调用库 I/O 函数。现在我有这段代码:

printf( "" );

它正式调用库 I/O 函数,但没有任何效果。

这是可观察到的行为吗?编译器允许消除它吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淡墨 2024-12-08 11:42:49

如果 sync_with_stdiotrue,则当然可以观察到。如果是这样,printf("") 会强制与 std::cout 输出同步,刷新先前缓冲的输出。

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.

带刺的爱情 2024-12-08 11:42:49

输出变得无效,这是可以观察到的

  • 如果输出被重定向并且文件被关闭、截断,或者
  • 如果流状态无论如何都是“坏”,则

关于sync_with_...的观点也非常相关

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

春庭雪 2024-12-08 11:42:49

我非常怀疑这一点,因为如果操作系统在调用 printf 的线程阻塞 I/O 时选择上下文切换,那么在多线程编程中该行为可能会变得更加明显。

在这种情况下,如果结果取决于线程的交错方式,那么它肯定会产生影响。

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.

永言不败 2024-12-08 11:42:49

理论上,您的 C 库可以按照根据时间刷新缓冲区的方式编写。在这种情况下,打印空字符串可能会导致刷新,从而产生可见的效果。

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.

提赋 2024-12-08 11:42:49

当然,这具有可观察的行为 - 它必须使用底层文件描述符生成对 write() 系统调用的调用。进行系统调用是非常容易观察到的行为。

考虑一个极端的例子,内核中的文件描述符可能由设备驱动程序提供服务,每次调用写文件操作时都会发出警报声(好吧,我承认有点人为的例子:-)...

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 :-) ...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文