c - 是否需要 %c fprintf 说明符来获取 int 参数

标签 c c99 language-lawyer printf variadic-functions

在 C99 标准的第 7.19.6.1 节第 8 段中:

c If no l length modifier is present, the int argument is converted to an unsigned char, and the resulting character is written.

在 C99 标准的第 7.19.6.1 节第 9 段中:

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

  • fprintf函数需要 int争论?

例如,将传递 unsigned int导致未定义的行为:

unsigned int foo = 42;

fprintf(fp, "%c\n", foo); /* undefined behavior? */

这让我很担心,因为实现可以定义 charunsigned char 具有相同的行为(第 6.2.5 节第 15 段)。

对于这些情况,整数提升可能会指示 charpromoted to unsigned int on some implementations .因此,留下以下代码可能会导致这些实现出现未定义的行为:

char bar = 'B';

fprintf(fp, "%c\n", bar); /* possible undefined behavior? */
  • int变量和文字 int常量是将值传递给 fprintf 的唯一安全方法与 %c说明符?

最佳答案

fprintf

%c 转换规范需要一个 int 参数。在 默认参数提升 之后,值必须是 int 类型。

unsigned int foo = 42;
fprintf(fp, "%c\n", foo);

未定义的行为:foo 必须是 int

char bar = 'B';
fprintf(fp, "%c\n", bar);

不是未定义的行为:bar 被提升(默认参数提升)为 int,因为 fprintf 是一个可变参数函数。

编辑:公平地说,仍有一些非常罕见的实现可能是未定义的行为。例如,如果 char 是一个无符号类型,并非所有 char 值都可以在 int 中表示(如 this implementation ),则默认参数对 unsigned int 进行了提升。

关于c - 是否需要 %c fprintf 说明符来获取 int 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17883640/

相关文章:

c++ - 私有(private)枚举访问无法从嵌套类的友元函数编译

c - 在 C 中如何使用指针递增变量?

c - 为什么 gcc99 指向无意义的错误而标准 gcc 没有?

c - C 结构中的灵活数组成员

c++ - 了解数组成员

c++ - 条件运算符 + upcast + const 引用

c - 这两个 char 声明有什么区别?哪一个是正确的?

c - 什么样的错误会影响以前的 C 语句?

c - 线性搜索与 strlen

C : How to make the size of an array dynamic?