问题描述
由于搜索 printf()
的大量结果,我只发现了非常不相关的问题.
I only found pretty unrelated questions due to the tons of results searching for printf()
.
为什么 uint8_t
不指定自己的格式字符串,而其他任何类型都指定?
Why does uint8_t
not specify its own format string but any other type does?
据我了解printf()
,它必须知道提供的参数的长度才能解析变量参数列表.
As far as I understand printf()
, it has to know the length of the supplied parameters to be able to parse the variable argument list.
由于 uint8_t
和 uint16_t
使用相同的格式说明符 %u
,printf()
怎么知道"要处理多少字节?或者在提供 uint8_t
时是否涉及到 uint16_t
的隐式转换?
Since uint8_t
and uint16_t
use the same format specifier %u
, how does printf()
"know" how many bytes to process? Or is there somehow an implicit cast to uint16_t
involved when supplying uint8_t
?
也许我遗漏了一些明显的东西.
Maybe I am missing something obvious.
推荐答案
printf()
是一个可变参数函数.它的可选参数(并且只有那些)根据默认参数提升(6.5.2.2.p6)得到提升.
printf()
is a variadic function. Its optional arguments( and only those ) get promoted according to default argument promotions( 6.5.2.2. p6 ).
由于您要求使用整数,因此在这种情况下会应用整数提升,并且您提到的类型将提升为 int
.(而不是 unsigned int
因为 C )
Since you are asking for integers, integer promotions are applied in this case, and types you mention get promoted to int
. ( and not unsigned int
because C )
如果您在 printf() 中使用 "%u"
,并将其传递给 uint16_t
变量,则该函数会将其转换为 int
,然后到一个 unsigned int
(因为你用 %u 要求它)然后打印它.
If you use "%u"
in printf(), and pass it an uint16_t
variable, then the function converts that to an int
, then to an unsigned int
( because you asked for it with %u ) and then prints it.
这篇关于为什么 uint8_t 和 uint16_t 的格式说明符相同 (%u)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!