格式说明的无符号字符 [英] Format specifier for unsigned char

查看:168
本文介绍了格式说明的无符号字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我要打印 unsigned char型

unsigned char x = 12;

这是正确的。这样的:

which is correct. This:

printf("%d",x);

或本

printf("%u",x);

问题是在其他地方SO我遇到这样的讨论:

The thing is elsewhere on SO I encountered such discussion:

- 即使与CH改为unsigned char型时,code的行为不是由C标准定义。这是因为unsigned char型被提升到一个int(在正常C实现),因此一个int被传递给printf的说明符%U。然而,%U期待一个unsigned int,所以类型不匹配,和C标准没有定义的行为

- 您的评论是不正确。该标准C11指出,转换说明必须是同一类型的函数参数本身,而不是推动型。这一点还特意在HH长度修改的说明问题:参数将根据整数促销活动已经推广,但其价值应在打印前被转换为签署char或unsigned char

因此​​,这是正确的?任何可靠的消息来源说,在这个问题上? (在这个意义上,我们也应该打印无符号短 INT%d条,因为它可以提升到 INT ?)。

So which is correct? Any reliable source saying on this matter? (In that sense we should also print unsigned short int with %d because it can be promoted to int?).

推荐答案

正确的是*:

printf("%d",x);

这是因为随着的printf()是可变参数的功能的默认参数提升的。这意味着 unsigned char型值总是晋升为 INT

This is because of default argument promotions as printf() is variadic function. This means that unsigned char value is always promoted to int.

从N1570(C11草案) 6.5.2.2/6 函数调用的(重点煤矿前进):

From N1570 (C11 draft) 6.5.2.2/6 Function calls (emphasis mine going forward):

如果它表示所调用的函数的前pression有一个类型,
  不包括样机,在整数促销活动执行上
  每一个参数,并且具有类型参数浮动被提升为
  双击。这些被称为的默认参数提升

If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.

6.5.2.2/7 小节讲述:

在一个函数原型声明符原因的省略号
  参数类型转换到最后声明参数后停止。
  在默认参数促销活动都在尾随参数执行

The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

这些整促销活动在 6.3.1.1/2 中定义的布尔,字符和整数的:

These integer promotions are defined in 6.3.1.1/2 Boolean, characters, and integers:

如果一个 INT 可以重新present原始类型的所有值(如限制
  由宽度为一个位域),值转换为 INT ;
  否则,将其转换为 unsigned int类型。这些被称为
  的整数促销 0.58)所有其它类型在整数不变
  促销活动。

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.

这句话回答您的第二个问题无符号短(见下面的评论)。

This quote answers your second question of unsigned short (see comment below).

*有例外,超过800位 unsigned char型(例如,它可能占用16位),见@ chux的的answer

* with exception to more than 8 bits unsigned char (e.g. it might occupy 16 bit), see @chux's answer.

这篇关于格式说明的无符号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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