以下程序的输出令人困惑。
uint16_t first = 10, second = 20, third = 30;
// printf("%p\n", &first);
scanf("%d", &second); // "%d" used intentionally.
printf("%" SCNu16 " ", first);
printf("%" SCNu16 " ", second);
printf("%" SCNu16 "\n", third);
随着第一个 printf
评论,我得到 10 20 0
。 (scanf
中的 "%d"
可能会导致此问题。如果我使用 "%"SCNu16
代替 ,效果很好%d
)。
当第一个 printf
取消注释时,我得到 0 20 30
。
令人困惑的是 - 为什么 printf
会导致输出差异?这是一贯的行为。
最佳答案
在您的代码中,
scanf("%d", &second);
是未定义的行为。 %d
期望参数是指向有符号整数类型 (int
) 的指针。
引用 C11
,第 §7.21.6.2 章,fscanf
函数
[...] Unless assignment suppression was indicated by a
*
, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
也就是说,SCNu
N
宏适用于 fscanf
系列,fprintf()
系列的对应项为 PRIu
N
。
关于c - uint16_t 与 printf 的值差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51302699/