Why does this if-statement combining assignment and an equality check return true?

后端 未结 4 688
醉梦人生
醉梦人生 2020-12-22 23:25

I\'ve been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this:

int i = 0;
if          


        
4条回答
  •  眼角桃花
    2020-12-23 00:04

    The actual answer is:

    1. The compiler gives precedence to "i == 0", which evaluates to true.
    2. Then it will evaluate i=1 as TRUE or FALSE, and since compiled assignment operators never fail (otherwise they wouldn't compile), it also evaluates to true.
    3. Since both statements evaluate as true, and TRUE && TRUE evaluates to TRUE, the if statement will evaluate to TRUE.

    As proof, just look at the asm output of your compiler for the code you entered (all comments are my own):

    mov     dword ptr [rbp - 8], 0    ; i = 0;
    cmp     dword ptr [rbp - 8], 0    ; i == 0?
    sete    al                        ; TRUE (=1)
    mov     cl, al
    and     cl, 1                     ; = operator always TRUE
    movzx   edx, cl
    mov     dword ptr [rbp - 8], edx  ; set i=TRUE;
    test    al, 1                     ; al never changed,
                                      ; so final ans is TRUE
    

    The asm output above was from CLANG, but all other compilers I looked at gave similar output. This is true for all the compilers on that site, whether they are pure C or C++ compilers, all without any pragmas to change the mode of the compiler (which by default is C++ for the C++ compilers)

    Note that your compiler did not actually set i=1, but i=TRUE (which means any 32-bit not zero integer value). That's because the && operator only evaluates whether a statement is TRUE or FALSE, and then sets the results according to that result. As proof, try changing i=1 to i=2 and you can observe for yourself that nothing will change. See for yourself using any online compiler at Compiler Explorer

提交回复
热议问题