Conditional operator “ ? : ”

后端 未结 3 1312
盖世英雄少女心
盖世英雄少女心 2021-01-13 18:24

I\'ve done my programming exam in C yesterday. There was a question I could not answer, and even though I\'ve studied today I can\'t come up with a solution.

So we h

相关标签:
3条回答
  • 2021-01-13 19:02

    Why not to surprise your teacher with very detailed explanation of what is happening ;)

        ...
        mov     eax, dword ptr [rbp - 16]       ; get C
        xor     eax, -1                         ; negate C
        mov     ecx, dword ptr [rbp - 8]        ; get A
        mov     edx, ecx                        ; put A into edx
        add     edx, -1                         ; add -1 to edx => A--
        mov     dword ptr [rbp - 8], edx        ; store result inside A
        sub     eax, ecx                        ; substract from ~C what was the result of A--
        mov     dword ptr [rbp - 8], eax        ; store it inside variable A
        ...
    
    0 讨论(0)
  • 2021-01-13 19:08

    The statement

    X = B != C ? A=(~C) - A-- : ++C + (~A);
    

    is equivalent to

    if(B != C)
        X = (A = (~C) - (A--));
    else 
        X = ++C + (~A);
    

    So, the expression A = (~C) - (A--) invokes undefined behavior. In this case nothing good can be expected.

    That said, this is a faulty question and shouldn't be asked in an examination. Or it could be asked with multiple choice answers as long as one option states that the code will invoke undefined behavior.

    0 讨论(0)
  • 2021-01-13 19:21

    This question should never be on an exam, because it contains undefined behavior.

    Specifically, this assignment A = (~C) - A-- modifies A twice - in the -- compound assignment, and in the assignment itself. Since there is no sequence point in between the two, the behavior is undefined.

    Note: This does not mean that the program is not going to print anything. It would most definitely produce some output on most platforms. However, none of that matters, because C the program is invalid in its entirety: it can produce any output it chooses to, produce no output, or even crash.

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