是否将负数打印为C中定义良好的字符? [英] Is printing negative numbers as characters well-defined in C?
问题描述
例如,以下代码:
#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
为负,仍然在屏幕上打印字符。我想知道这种行为是否定义明确吗?
When a
and b
are negative, characters are still printed on the screen. I wonder whether this behaviour is well-defined?
如果是,是由标准定义还是由特定实现定义?定义这种行为的意义何在?
If so, is it defined by the standard or an specific implementation? And what's the point of defining such behaviour?
推荐答案
是
传递值以匹配%c
是由于 int
或 unsigned
作为通常的整数促销的一部分> ... 自变量 printf()
。
When a value is passed to match "%c"
is it converted to an int
or unsigned
as part of the usual integer promotions due to the ...
of the printf()
arguments.
当 printf()
看到 int
的值,它将转换为 unsigned char
When printf()
see that int
value, it converts to to an unsigned char
. Then the corresponding character is printed.
c
如果没有l
长度修饰符存在,int
参数转换为unsigned char
,并生成c写作。 C11dr§7.21.6.18
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 $ c的窄型整数$ c>甚至在
INT_MAX
范围内的 unsigned
都不是问题。
So passing any narrow type integer that is promoted to int
or even an unsigned
within the range of INT_MAX
is not a problem.
这篇关于是否将负数打印为C中定义良好的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!