How does the increment operator work in an if statement?

假装没事ソ 提交于 2019-12-01 19:33:33

问题


    #include <stdio.h>

    int main()
    {
        int x = 0;

        if (x++)
            printf("true\n");
        else if (x == 1)
            printf("false\n");
        return 0;
    }

Output:

false

Why is the output false?

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.


回答1:


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




回答2:


Post increment means that it returns the current value (in this case for the purpose of the if) and increments it afterwards. It is equivalent to

if(x) {
  x++;
  // ...
} else {
  x++;
  // ...
}



回答3:


0 is equivalent to false in C. As you are using post-increment operator, condition is evaluated before increment so x is false and printf("true\n"); is never executed. Then goes to else and succeeds evaluating x == 1, then prints false.

As a good practice, try to avoid assignations in condition sentences.




回答4:


0 is false in C. You're using the post-increment operator.




回答5:


You yourself wrote: "x++ is post increment, this means that the value of x is used then it is incremented"

Consider what that means:

  1. x is 0

  2. The expression is evaluated, 0 is false, so the expression is false.

  3. The post increment happens, changing x from 0 to 1.
    (After the expression was evaluated)




回答6:


I believe this simply could fix the error


#include <stdio.h>

    int main()
    {
        int x = 0;

        if (++x)
            printf("true\n");
        else if (x == 1)
            printf("false\n");
        return 0;
    }


来源:https://stackoverflow.com/questions/21435072/how-does-the-increment-operator-work-in-an-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!