How does the increment operator work in an if statement?

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

    My opinion is that a better response to the relation between 'if' statement and the post increment operator '++' requires the expansion of your C-code into Assembly. Trying to figure it out under the constricting logic of blocks of the "if ... else" statement, of high level languages, might be misleading because the flow control is read in different terms.

    Consider that the pre and the post operators rely on the "change-then-use" and on the "use-then-change" rules respectively, where 'change' is meant by 'increment' and 'use' by the 'comparison'. So your input C-code basically turns into this raw pseudo-assembly:

    ; evaluating the first condition
    mov x,0 // set x = 0
    cmp x,0 // use (for comparison)
    inc x // then change (now x is 1)
    je print1
    ; evaluating the second condition
    mov eax,1
    cmp eax,x // evaluates to true
    je print2
    
    print1:
       printf("true\n");
    
    print2:
      printf("false\n");
    

    Take care that compilers might not put the inc instruction at the same position, that is, at the top or at the bottom of the labelled block of instructions. Hope it helps!

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-13 14:40

    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++;
      // ...
    }
    
    0 讨论(0)
  • 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".

    0 讨论(0)
  • 2021-01-13 14:51

    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;
        }
    
    0 讨论(0)
  • 2021-01-13 14:52

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

    0 讨论(0)
提交回复
热议问题