说我要打印unsigned char
:
unsigned char x = 12;
哪个是对的。这:
printf("%d",x);
or this:
printf("%u",x);
?
事情在其他地方,所以我遇到了这样的讨论:
- 即使 ch 更改为 unsigned char,代码的行为也不是由 C 标准定义的。这是因为 unsigned char 被提升为 int(在正常的 C 实现中),因此 int 被传递给 printf 作为说明符 %u。但是,%u 需要一个无符号整型,因此类型不匹配,并且 C 标准没有定义该行为
-你的评论不正确。 C11 标准规定转换说明符必须与函数参数本身具有相同的类型,而不是提升的类型。这一点在 hh 长度修饰符的描述中也得到了具体解决:“参数将根据整数提升进行提升,但在打印之前其值应转换为有符号字符或无符号字符”
那么哪个是正确的呢?关于此事有可靠消息来源吗? (从这个意义上说,我们还应该打印unsigned short
int 与 %d 因为它可以提升为int
?).
正确的是*:
printf("%d",x);
这是因为默认参数促销 as printf()
是可变参数函数。这意味着unsigned char
价值总是被提升为int
.
来自 N1570(C11 草案)6.5.2.2/6
函数调用(强调我的未来):
如果表示被调用函数的表达式的类型为
不包括原型,整数促销执行于
每个参数以及具有类型的参数float
被提升为double
。这些被称为默认参数促销.
and 6.5.2.2/7
子条款告诉:
函数原型声明符中的省略号表示法导致
参数类型转换在最后一个声明的参数之后停止。
这默认参数提升是在尾随参数上执行的.
这些整数提升定义在6.3.1.1/2
布尔值、字符和整数:
If an int
can represent all values of the original type (as restricted
by the width, for a bit-field), the value is converted to an int
;
otherwise, it is converted to an unsigned int
. These are called the
integer promotions.58) All other types are unchanged by the integer
promotions.
这句话回答了你的第二个问题unsigned short
(见下面的评论)。
* with exception to more than 8 bits unsigned char
(e.g. it might occupy 16 bit), see @chux's answer https://stackoverflow.com/a/27552302/586873.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)