How does the increment operator work in an if statement?

前端 未结 7 1456
感情败类
感情败类 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:37

    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.

提交回复
热议问题