Conditional operator “ ? : ”

后端 未结 3 1313
盖世英雄少女心
盖世英雄少女心 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: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.

提交回复
热议问题