I learned today C中的scanf()
不判断整数是否可在指定类型中表示.例如:
#include <stdio.h>
int main(void)
{
short num;
int ret = scanf("%hd", &num);
printf("read %d, returned %d\n", num, ret);
return 0;
}
在我的系统(Clang/MacOS)上,上面的程序将显示"返回1",意思是scanf()
读取指定的令牌,即使输入不可表示,例如4223215425243525443245234453
.man scanf
说:
当输入字符与此类格式字符不匹配时,扫描停止.当无法进行输入转换时,扫描也会停止.
Does the C standard require this behavior,或者是否也允许scanf()
的实现者将超出范围的数字输入视为无效(因此在类似上面的情况下返回0)?如果这种行为是必需的,我希望引用标准中的话来说明.