问题
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 printf
s?
回答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