gpt4 book ai didi

c - `printf("%.-1s\n", "foo")` 会调用未定义的行为吗?

转载 作者:太空狗 更新时间:2023-10-29 17:10:59 26 4
gpt4 key购买 nike

根据the standards :

Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

  • Zero or more flags [...].
  • An optional minimum field width. [...]
  • An optional precision that gives [...] the maximum number of bytes to be written for s conversions. The precision takes the form of a period (.) followed by [...] an optional decimal integer;
  • An optional length modifier [...]. + A conversion specifier character [...].
  • An optional minimum field width. [...]
  • A conversion specifier character [...].

稍后:

A negative precision argument is taken as if the precision were omitted.

我对 printf("%.-1s\n", "foo") 的期望根据我对标准定义的解释:

我从标准中引用的第二个引述表明我们可以传递一个负精度参数,这样的精度将被忽略。

所以,printf("%.-1s\n", "foo")应该等同于 printf("%s\n", "foo") , 这将显示 "foo\n"并返回 4 .

然而,这里是实际的printf("%.-1s\n", "foo")我使用的系统 (osx) 上的行为:

printf("%.-1s\n", "foo")显示器 " \n"并返回 2 .

这显然与我的预期不同。

  • 我对标准的解释是否有误?
  • 此行为是否未定义?
  • 传递负精度(编辑:不带星号)真的可行吗?

最佳答案

N1570-§7.21.6.1/p5:

As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.

标准指定仅当星号用作格式字符串中的精度并且负值作为参数传递时才适用,如下所示

printf("%.*s\n", -1, "foo");  // -1 will be ignored  

在第 4 段中它说:

[...] The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; [...]

但它没有具体说明十进制整数是否应大于0(如7.21.6.2节中scanf的字段宽度所述/p3).此时标准似乎模棱两可,结果可能取决于机器。

关于c - `printf("%.-1s\n", "foo")` 会调用未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44638909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com