“%c"的默认参数提升和相关性;在 printf 中 [英] default argument promotions and relevance of "%c" in printf

查看:61
本文介绍了“%c"的默认参数提升和相关性;在 printf 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 libc 关于可变参数函数的说明:

Here's what libc has to say about variadic functions:

由于原型没有指定可选参数的类型,在对可变参数函数的调用中,默认参数提升是在可选参数值上执行的.这意味着 char 或 short int 类型的对象(无论是否有符号)被提升为 int 或 unsigned int,视情况而定;并且 float 类型的对象被提升为 double 类型.所以,如果调用者传递一个 char 作为可选参数,它会被提升为一个 int

Since the prototype doesn’t specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int

那么,为什么有人会在 printf 中使用 "%c""%hd" ?他们应该只使用 "%d".

Then, why would anyone use "%c", or "%hd" in printf ? they should just use "%d".

我还看到 float 没有格式说明符.float 必须与用于 double%f 一起使用,因为由于促销,不可能接收浮点数作为可变参数.

I also see that there's no format specifier for float. float has to live with %f which is for double since due to promotions, it's not possible to receive a float as a variadic argument.

我知道对于 scanf,参数是指针,不会发生任何提升.

I know for scanf, the arguments are pointers and no promotion happens.

是否有任何原因让我想念 "%c" 为什么和何时必须存在于 printfs?

Is there any reason I am missing why and when "%c" must exist for printfs?

推荐答案

那么,为什么会有人在 printf 中使用%c"或%hd"?他们应该只使用%d".

Then, why would anyone use "%c", or "%hd" in printf ? they should just use "%d".

人们会使用 %c 将整数解释为其字符代码(即打印 'A' 而不是 65).可以使用 %hd 来指示 printf 删除 short 的上部,该部分可能已作为符号扩展短的一部分添加传入的值.两种格式都提供了对 int 的另一种解释.

One would use %c to interpret the integer as its character code (i.e. print 'A' instead of 65). One would use %hd to instruct printf to drop the upper portion of the short that may have been added as part of sign-extending the short value passed in. Both formats offer an alternative interpretation of an int.

我还看到 float 没有格式说明符.

I also see that there's no format specifier for float.

正确:由于值已提升为double,因此不需要单独的标志.

That's correct: since the value has been promoted to double, there is no need for a separate flag.

这篇关于“%c"的默认参数提升和相关性;在 printf 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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