是否将负数打印为C中定义良好的字符? [英] Is printing negative numbers as characters well-defined in C?

查看:68
本文介绍了是否将负数打印为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 no l length modifier is present, the int argument is converted to an unsigned char, and the resulting character is written. C11dr §7.21.6.1 8

因此,传递任何提升为 int 甚至在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆