增量运算符如何在if语句中工作? [英] How does the increment operator work in an if statement?
本文介绍了增量运算符如何在if语句中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
int main()
{
int x = 0;
if (x++)
printf("true\n");
else if (x == 1)
printf("false\n");
return 0;
}
输出:
false
为什么输出错误?
x++
是发布增量;这意味着使用x
的值,然后将其递增.
如果是这样,则应使用x=0
,并且答案应为真.
x++
is post increment; this means that the value of x
is used then it is incremented.
If it is so, then x=0
should be used and the answer should be true.
推荐答案
在C中,0
被视为false
.在x++
中,在表达式中使用x
的值,即0
,它变为
In C, 0
is treated as false
. In x++
, the value of x
, i.e, 0
is used in the expression and it becomes
if(0) // It is false
printf("true\n");
if
的正文未执行.之后,x
现在是1
.现在检查else if
中的条件,即x == 1
.由于x
是1
,因此此条件的值为true
,因此它的主体被执行并打印"false"
.
The body of if
doesn't get executed. After that x
is now 1
. Now the condition in else if
, i.e, x == 1
is checked. since x
is 1
, this condition evaluates to true
and hence its body gets executed and prints "false"
.
这篇关于增量运算符如何在if语句中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文