【发布时间】:2012-01-31 18:10:49
【问题描述】:
我有以下程序
#include <stdio.h>
int main(void)
{
unsigned short int length = 10;
printf("Enter length : ");
scanf("%u", &length);
printf("value is %u \n", length);
return 0;
}
当使用gcc filename.c 编译时发出以下警告(在scanf() 行中)。
warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 2 has type ‘short unsigned int *’ [-Wformat]
然后我引用了C99 specification - 7.19.6 Formatted input/output functions,但在将长度修饰符(如short、long 等)与unsigned 一起用于int 数据类型时,我无法理解正确的格式说明符。
%u 是正确的说明符 unsigned short int 吗?如果是这样,为什么我会收到上述警告?!
编辑:
大多数时候,我都在尝试%uh,但它仍在发出警告。
【问题讨论】:
-
printf("%u\n", (unsigned int)length); //始终有效,因为您阅读的 C99 规范保证sizeof(short) <= sizeof(int)(但下面这个问题的实际答案当然要好得多) -
不需要演员表;默认促销会处理它。