如果输入是一个字符,为什么这段代码输出64?

InK*_*ght 0 c scanf

#include <stdio.h>
#include <stdlib.h>

//A simple program that asks for an integer and prints it back out.

int main()
{
    int a; 
    printf("Type an integer: ");
    scanf("%d",&a);
    printf("The integer you typed is: %d",a);
}
Run Code Online (Sandbox Code Playgroud)

如果用户输入一个字符,X那么由于某种原因输出总是64.为什么会这样?

Sou*_*osh 9

这会调用未定义的行为.

如果发生匹配失败scanf()("X"不匹配%d),则提供的参数保持未分配状态,并且由于参数是未初始化的局部变量,该值仍然是不确定的.

相关的,来自C11章节§7.21.6.2

[...]如果输入项不是匹配序列,则指令的执行失败:此条件是匹配失败.[...]

尝试使用该值会调用UB.从C11附件J.2,未定义的行为

具有自动存储持续时间的对象的值在不确定时使用.

因此,你应该永远

  1. 初始化您的局部变量
  2. 检查返回值scanf().