增量运算符如何在if语句中工作? [英] How does the increment operator work in an if statement?

查看:86
本文介绍了增量运算符如何在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.由于x1,因此此条件的值为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆