以下代码的输出是什么?
#include <stdio.h>
int n;
int main() {
scanf("&d", &n);
switch (n) {
case 1:
printf("hello\n");
break;
case 2:
printf("good\n");
break;
default:
printf("Morning\n");
break;
}
return 0;
}
大多数人预计会出现错误,但在执行时,无论输入什么,它总是输出 Morning
。
最佳答案
输出总是Morning
。
scanf("&d")
期望输入两个字符 &
和 d
,字面意思。如果您键入任何其他内容,scanf
调用将失败。但是,您的代码不检查 scanf
的返回值,因此没有任何区别。
scanf
的&n
参数被忽略,因为在格式化字符串。因此(正如 C 标准所述(C99,7.19.6.2 fscanf
函数/2)):
If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.
scanf("&d", &n)
因此等同于 scanf("&d")
。
当 switch (n)
检查 n
时,它仍将包含初始化时使用的值。没有明确的初始化器,所以它被设置为 0
(因为它是一个全局变量(具体来说,因为它有静态存储;参见 C99, 6.7.8 Initialization/10 )).
没有 case 0:
标签,所以 default:
开始。
关于c - scanf 的 PlaceHolder 中的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52227574/