【发布时间】:2018-02-09 07:30:03
【问题描述】:
我注意到在 C 中,我的布尔变量以某种我不理解的方式发生了变化。
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool x, y;
printf("x: ");
scanf("%d", &x);
printf("x is %d\n", x);
printf("y: ");
scanf("%d", &y);
printf("x is %d\n", x);
printf("y is %d\n", y);
return 0;
}
如果我为x 输入一个值1 并为y 输入任何值(在此示例中为1):
x: 1 x is 1 y: 1 x is 0 y is 1
最后,y 输出正确的原始值,但 x 在两者之间神奇地变为0!
当x 的输入是0 时,这不是问题,因为x 和y 的输出都是它们各自的预期值。
请解释发生了什么!
【问题讨论】:
-
旁注:始终检查
scanf函数的返回值。否则,当用户提供无效(在本例中为非数字)输入时,您将遇到 未定义的行为。 -
节省时间,启用编译器警告。
bool x, y; ... scanf("%d", &x);应该警告过你。 -
@chux 我同意,我添加了这个作为答案。