问题
Consider following program:
#include <stdio.h>
int main()
{
short a=9;
//printf("%hi\n",a);
printf("%d",a); // LINE 6
}
According to this the format specifier for short type (signed) is %hi
Is the short type variable always gets promoted automatically to int before performing any operation on it? Is it undefined behavior ,
If I use %d format specifier to print the value of variable in this program? I compiled it using gcc -Wall -Wextra -WFormat
options but still
compiler isn't showing any single warning. Why?
回答1:
printf("%hi\n", a);
a
is promoted to int
as per the rules of default argument promotion of variadic functions.
Anyway as you use h
specifier the implementation is allowed to expect the int
value is within SHRT_MIN
or SHRT_MAX
limits. Passing a value outside the bounds is undefined behavior.
Of course printf("%i\n", a);
is also valid because of the int
promotion of a
so using %hi
conversion specification is not very usual.
来源:https://stackoverflow.com/questions/32528580/confusion-about-short-data-type-format-specifier-in-c