为什么int的值会改变?

Mik*_*eri 2 c

我有这个C代码:

int a = 5;
printf("a is of value %d before first if statement. \n", a);
if (a = 0) {
    printf("a=0 is true. \n");
}
else{
    printf("a=0 is not true. \n");
}
printf("a is of value %d after first if statement. \n", a);
if (a == 0){
    printf("a==0 is true. \n");
}
else{
    printf("a==0 is not true. \n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

a is of value 5 before first if statement.
a=0 is not true. 
a is of value 0 after first if statement. 
a==0 is true. 
Program ended with exit code: 0
Run Code Online (Sandbox Code Playgroud)

我不明白为什么int值在第一个语句中仍被识别为5,但在第二个if之前更改为0,或者为什么它会发生变化?

Luk*_*e19 12

当你这样做时,if (a = 0)你将变量设置a0.在C中,这也将评估表达式0.

实际上,if语句分两步完成.就像你做的那样:

a = 0; //assign 0 to a

if (a) {  ... } //evaluate a to check for the condition
Run Code Online (Sandbox Code Playgroud)

在这种情况下,因为a0,它评估为false.这就是为什么你最终在else第一部分,在第二部分(a == 0)评估到true!


小智 5

在第一个如果您需要使用"==".

if(a == 0) {
Run Code Online (Sandbox Code Playgroud)