How does the increment operator work in an if statement?

前端 未结 7 1429
感情败类
感情败类 2021-01-13 14:16
    #include 

    int main()
    {
        int x = 0;

        if (x++)
            printf(\"true\\n\");
        else if (x == 1)
            printf(         


        
7条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 14:49

    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");  
    

    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".

提交回复
热议问题