在 C99 标准的第 7.19.6.1 节第 8 段中:
c
If nol
length modifier is present, theint
argument is converted to anunsigned 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? */
这让我很担心,因为实现可以定义 char
与 unsigned char
具有相同的行为(第 6.2.5 节第 15 段)。
对于这些情况,整数提升可能会指示 char
待promoted 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/