例如下面的代码:
#include <stdio.h>
#include <limits.h>
int main(void)
{
char a;
signed char b;
for(a = CHAR_MIN, b = CHAR_MIN; a < CHAR_MAX ; a++, b++ )
printf("%c %c\n", a, b);
}
输出:
! !
" "
# #
$ $
% %
& &
' '
( (
……
当a
和b
为负数时,字符仍然打印在屏幕上。我想知道这种行为是否定义明确?
如果是这样,它是由标准还是特定实现定义的?定义此类行为的意义何在?
最佳答案
是
当传递一个值来匹配 "%c"
时,它是否被转换为 int
或 unsigned
作为通常整数提升的一部分由于 printf()
参数的 ...
。
当 printf()
看到 int
值时,它会转换为 unsigned char
。然后打印相应的字符。
c
If nol
length modifier is present, theint
argument is converted to anunsigned char
, and the resulting character is written. C11dr §7.21.6.1 8
因此,传递任何提升为 int
或什至 INT_MAX
范围内的 unsigned
的窄类型整数都不是问题。
关于c - 将负数打印为 C 中明确定义的字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36166698/