微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – printf在同一个调用中%n的值 – 无意义?

我在 cppreference.com没有找到printf规范的下列部分的意图:

There is a sequence point after the action of each conversion
specifier; this permits storing multiple %n results in the same
variable and printing the value stored by %n earlier within the same
call.

这读取好像一个(甚至几个)%n转换说明符的结果可以打印在同一个printf语句中.
但是我无法找到如何实现这一点,因为传入printf调用的所有参数都是在printf的正文输入之前进行评估(在参数评估后有一个序列点).因此,在printf有机会用“到目前为止写入的字符数”之前,会对%n写入的变量的值进行评估.

#include <stdio.h>

int main( int argc,char* argv[] )
{
    int n = 0;
    printf("Hello,world!%n (%d first n); %n (%d second n)",&n,n,n);
    // will print out "Hello,world! (0 first n);  (0 second n)"

    return 0;
}

我的问题:如果没有任何机会“在同一个电话中打印%n存储的值”,那么printf规范的相应部分不是无意义还是误导?

c99 standard声明的实际意义是什么?

7.19.6 Formatted input/output functions
(1) The formatted input/output functions shall behave as if there is a sequence point after the
actions associated with each specifier.

是减少获得未定义行为的“机会”吗?

这个问题用c和c标记,因为我认为这个主题对两种语言都是一样的.

解决方法

您的代码确实只打印零,原因是您已经正确识别.

标准中的声明仍然是必要的,因为在其他地方,如果一个对象被写入不止一次而没有插入的序列点,则程序的行为是未定义的.实际上,声明是必要的,你的代码不具有未定义的行为(不像i = i;).

原文地址:https://www.jb51.cc/c/116152.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐