default argument promotions and relevance of “%c” in printf

℡╲_俬逩灬. 提交于 2021-01-29 02:25:36

问题


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

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

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

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.

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

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


回答1:


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

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.

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

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



来源:https://stackoverflow.com/questions/28782282/default-argument-promotions-and-relevance-of-c-in-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!