如果 scanf() 得到一些与格式字符串不匹配的字符会发生什么?

What will happen if scanf() gets some character which doesn't match the format string?

#include <stdio.h>

int main(void)
{
    int i, j, k;
    scanf("%d%d%d", &i, &j, &k);
    printf("%d %d %d", i, j, k);
    return 0;
}

如果我们输入1,2,3,会发生什么?为什么?

根据 ,如果 scanf() 读取了一个意外的字符串,它会提前 return 因此不会修改最后一个成功值之后的任何值。

我试过clang(LLVM 6.1.0),在-O0上,上面的解释是正确的,但是在-O2上,第二个变量总是一个随机数,但和以前不一样scanf(),第三个变量总是0

给出的explanation是正确的。 scanf 将停止,return 将在输入中找到 ,。因此 jk 将未初始化。未初始化的变量具有不确定的值,如果它是陷阱表示,这将调用未定义的行为。

根据 the manualscanfs return 值告诉您使用这些参数是否安全。

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned

如果您要输入 1,2,3,那么 scanf 将 return 1,表示第一个参数可以安全使用并且匹配失败发生在首先 , 因为它与根据格式字符串预期的输入不匹配。

如果您在此之后使用 jk,那么您的代码将使用不确定的值,这是未定义的行为,显然是不稳定行为的来源避免...您 检查 scanf 的 return 值非常重要,因为您使用的 link 也鼓励。