confusion about short data type format specifier in C

一个人想着一个人 提交于 2019-12-10 10:06:52

问题


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

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