How does the increment operator work in an if statement?

前端 未结 7 1428
感情败类
感情败类 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!

提交回复
热议问题