C为什么将unsigned short int解释为unsigned long?

问题描述

在此主要功能中,我收到一条错误消息,我不应该使用%hu(无符号短格式的格式说明符),并且无符号短类型显示为无符号长。怎么可能呢?

#include <stdio.h>

int main (void) {
    unsigned short int a,b,c;
    printf("sizeof short int - %hu bytes \n\n",sizeof(unsigned short int));
}

shell输出为:

warning: format specifies type
      'unsigned short' but the argument has type
      'unsigned long' [-Wformat]
  ...%hu bytes \n\n",sizeof(unsigned short int));
     ~~~              ^~~~~~~~~~~~~~~~~~~~~~~~~~
     %lu

解决方法

sizeof运算符的结果为size_t,无论传递给它什么。

N1570引用6.5.3.4 sizeof和_Alignof运算符:

2 sizeof运算符产生其操作数的大小(以字节为单位),它可以是 表达式或类型的括号名称。大小由以下类型决定 操作数。结果是一个整数。如果操作数的类型是可变长度数组 类型,对操作数求值;否则,不评估操作数,结果为 整数常量。

5 两个运算符的结果值都是实现定义的,其类型( 无符号整数类型)为size_t,在(和其他标头)中定义。

要打印size_t的格式说明符是%zu